Introduction to JavaScript Programming

JavaScript_ is the main programming language for web pages

that’s because essentially all web browsers have JavaScript built into them

because of this, JavaScript is one of the most popular and commonly used programming languages ever invented

JavaScript programs run inside a user’s web browser

using JavaScript, you can read and modify a web page’s DOM representation in pretty much any way imaginable

you can also use it to for animation, graphics, sounds, and pretty much anything else you can imagine doing in a web browser

there are hundreds of JavaScript libraries and add-on packages that you can use to do all sorts of interesting and useful things

aside: JavaScript can also be used outside a web browser, e.g. Node.js refers to the use of JavaScript outside of a web browser; we won’t be discussing Node.js in this course

A Bit of History

JavaScript was developed over 10 days in 1995 by Brendan Eich

it was originally called Mocha, and then LiveScript, and then JavaScript

JavaScript has an official international standard, and so standard JavaScript is sometimes called ECMAScript

Using JavaScript

there are three main ways to use JavaScript

  1. in the console: in the Chrome web developer console (type ctrl-shift-C to get to it Windows)

    this is good for testing small bits of JavaScript code

  2. internal JavaScript: in the head element of your page, put JavaScript in a script element:

    <head>
        ...
    
        <script>
    
           //
           // ... JavaScript goes here ...
           //
    
        </script>
    
        ...
    </head>
    
  3. external JavaScript: in the head element of your page, load a .js file using a script element like this:

    <head>
        ...
    
        <script src="scripts/mycode.js"></script>
    
        ...
    </head>
    

JavaScript as a (super) Calculator

lets start learning the basics of JavaScript by typing in some JavaScript expressions in the Chrome console (e.g. ctrl-shift-C in Chrome on Windows)

here’s a transcript of some JavaScript expression typed into the Chrome console:

> 25 * 3
75

> 1 + 2 + 3
6

> 2/4
0.5

> 1/3 + 1/3 + 1/3
1

> 1 + 2 * 3
7

> (1 + 2) * 3
9

the > is the input prompt, and indicates what was typed in

the line underneath a > is what was returned by JavaScript

as you can see, JavaScript lets you do basic arithmetic in the usual way

* is multiplication, / is division, + is addition, - is subtraction

% is remainder, e.g. a % b is equal to the remainder when a is divided by b:

> 10 % 2
0

> 10 % 3
1

> 25 % 5
0

> 25 % 20
5

> 25 % 6
1

JavaScript follows the usual rule of evaluating multiplication before addition, and lets you use brackets to change the order of evaluation:

> 1 + 2 * 3
7

> (1 + 2) * 3
9

JavaScript numbers can be whole numbers like -56, 0, 22, etc.

or they can have decimal points in them, e.g. -34.221, 0.00351, 45.0, etc.

here’s the min and max values of JavaScript numbers:

> Number.MIN_VALUE
5e-324

> Number.MAX_VALUE
1.7976931348623157e+308

the number 5e-324 is the smallest positive number that JavaScript can represent, and its in exponential notation, and means \(5\times 10^{-324}\)

similarlly, 1.7976931348623157e+308 is the biggest JavaScript number, and it is \(1.7976931348623157 \times 10^{308}\)

while you don’t need to memorize these numbers, you could keep them in mind because sometimes they could cause problems

Variables

you can save values in variables, e.g.:

> age = 18
18

> 2 * age + 1
37

> cost = 11.99
11.99

> tax_rate = 0.05
0.05

> cost * tax_rate
0.5995

> tax = cost * tax_rate
0.5995

in general, we call this an assignment statement:

v = expr

v is a declared variable, while expr is some JavaScript expression

Other Kinds of Assignment

suppose tax_rate has the value 0.05

suppose we want to add 0.01 to it

one way to do that is like this:

> tax_rate
0.05

> tax_rate = tax_rate + 0.01
0.060000000000000005

> tax_rate
0.060000000000000005

note a couple of things here

first, the new tax_rate is 0.060000000000000005, and not 0.06

that’s because computers represent decimal numbers in a way that cannot avoid small round-off errors like this

0.060000000000000005 is so close to 0.06 that the it hardly matters for most practical computations

second, this statement would look pretty suspicious in a math class:

tax_rate = tax_rate + 0.01

in math, a = b means “a and b have the same value”, but in JavaScript a = b means “assign the value of expression b to variable a

so, in math, a statement like x = x + 1 means “x and x + 1 have the same value”, and so if you were to subtract x from both sides you get 0 = 1 — which is nonsensical!

but JavaScript = is not math =!

in JavaScript, x = x + 1 means “put the value of x + 1 into x”, which is the same as adding 1 to x

+= and -=

adding something to a variable is so common that JavaScript provides some special assignment operators to make it easier

for example, these two statements do the same thing:

tax_rate = tax_rate + 0.01

tax_rate += 0.01

the statement a += b, means that the value of b is added to a

similarly, the statement a -= b means that the value of b is subtracted from the a

both += and -= are quite common in JavaScript code since they tend to be quite short and readable

Common Math Functions

JavaScript comes with a number of pre-defined mathematical functions, e.g.:

> Math.sqrt(2)
1.4142135623730951

> Math.round(3.3)
3

> Math.floor(3.9)
3

> Math.ceil(3.001)
4

> Math.pow(2, 3)  // 2 to the power of 3
8

> Math.max(1/2, 1/3)
0.5

> Math.random()
0.48952779587096873

> Math.random()
0.8711466228069142

Math.random() returns a number chosen randomly from the range [0, 1)

notice the range is asymmetric, i.e. Math.random() could possibly return 0, but it will never return 1

so this is true: 0 <= Math.random() < 1

you can find all the pre-defined math functions in any JavaScript reference, such as this

Example: Simulating Rolling a 6-Sided Die

as an example of using JavaScript math functions, lets see how to simulate rolling a 6-sided die

when you roll a 6-sided die, one of the numbers 1, 2, 3, 4, 5, or 6 lands face up

we can generate random numbers in JavaScript with Math.random(), which returns a random number in the range [0, 1)

for example:

r = random()  //  0 <= r < 1

however, for a 6-sided die, we want the range to be [1, 6]

we can get that by doing a little bit of arithmetic on r

  • 0 <= r < 1
  • 6 * 0 <= 6*r < 6 * 1 (multiply each part by 6)
  • 0 <= 6r < 6 (simplify)
  • 0 + 1 <= 6r + 1 < 6 + 1 (add 1 to each part)
  • 1 <= 6r + 1 < 7 (simplify)

this means the expression 6*r+1 is in the range [1, 7)

it could be any number in that range, e.g. 1.5, 6.88, 3.0, etc.

the Math.floor function will remove digits after the decimal, and so this expression should return whole numbers from 1 to 6: Math.floor(6 * r + 1)

for example:

> r = Math.random()
0.438248162118164

> Math.floor(6 * r + 1)
3

> Math.floor(6 * r + 1)
3

every time you call Math.floor(6 * r + 1) you get the same value because r hasn’t changed

if you want a different value each time, replace r with Math.random(), e.g.:

> Math.floor(6 * Math.random() + 1)
1

> Math.floor(6 * Math.random() + 1)
1

> Math.floor(6 * Math.random() + 1)
4

> Math.floor(6 * Math.random() + 1)
3

Basic Strings

JavaScript variables can store strings as well as numbers

for example:

> name = 'Donald';

> name
"Donald"

a string is a sequence of 0, or more, characters

'Donald' is an example of a string literal

in JavaScript, string literals begin and end with ' characters

or, alternatively, a string literal can begin and end with " characters

you can combine strings using +, e.g.:

> 'Donald' + ' ' + 'Duck'
"Donald Duck"

this is called string concatenation

all strings have a property called length that tells you how many characters are in the string, e.g.:

> s = 'apple'
"apple"

> s.length
5

> "cat".length
3

JavaScript strings are immutable, i.e. once they are created their length and characters cannot be changed

Alerts

a simple way to get the user’s attention in JavaScript is to use the alert function

try typing this into the JavaScript console:

> alert('Hello!')

this causes a dialog box to pop up and requires the user to click a button dismiss it

alert is mostly useful when developing programs — it is often too intrusive for finished programs

The prompt Function

you can get a string from the user for a string using the prompt function, e.g.:

> name = prompt('Who are you?')
"Donald"

> name
"Donald"

prompt causes a dialog box to pop up that asks the user to type a string

whatever string the user types is then assigned to the variable name

like alert, prompt tends to be most useful when you are developing JavaScript programs, but it tends to be too intrusive in programs designed for ordinary users

Logic: === and !==

boolean values are an important type of data in JavaScript

there are only two boolean values: true and false

when you compare two numbers or strings, the result is a boolean value

x === y evaluates to true if x and y are the same, and false otherwise

x !== y evaluates to true if x and y are different, and false otherwise

for example:

> x = 4
4

> y = 3
3

> x === y
false

> x !== y
true

> x === x
true

> y !== y
false

they also work with strings:

> s = "apple"
"apple"

> t = "orange"
"orange"

> s === t
false

> s !== t
true

> t === t
true

be careful: x = y and x === y are very different!

x = y is an assignment statements: it copies the value of y into x

x === y is a comparison: it evaluates to true if x and y are the same, and false otherwise; === does not change the value of either x or y

Warning

JavaScript also lets you use x == y to compare values, but you should generally avoid it; the problem with x == y is that it has counter-intuitive result when x and y are not the same type, e.g.:

> 0 == ''
true

> 0 == '0'
true

> '' == '0'
false

x === y checks both the type and values of x and y, and so gives more sensible results:

> 0 === ''
false

> 0 === '0'
false

> '' === '0'
false

Logic: <, >, <=, and >=

x < y is true when x is less than y

x > y is true when x is greater than y

x <= y is true when x is less than, or equal to, y

x >= y is true when x is greater than, or equal to, y

if x and y are strings, then these comparisons check for alphabetical order, e.g.:

> "mouse" < "bat"
false

> "cat" <= "cattle"
true

Logic: &&, ||, and !

a boolean expression is any expression that evaluates to either true or false

for example, these are all boolean expressions: true, false, 2 === 3, 'cat' <= 'bat', x > y

you can combine boolean expressions using these logic operators

x && y means “x and y”, and evaluates to true when both x and y are true, and false otherwise

x || y means “x or y`"`, and evaluates to ``true when either x is true, or y is true, or both x and y are true

!x means “not x”, and evaluates to true if x is false, and false if x is true

&&, ||, and ! are important and will be used all the time — memorize them!

Moving on to Programs

we’ve introduced many of the basic elements of JavaScript expressions, and so the next step will be to write some large programs