JavaScript Crash Course Notes
Note: All the example files from this course are in a file named examples.zip, which you can download at tinyurl.com/jsccexamples There is also an online course for the book at tinyurl.com/jsccourse.
Introduction to JavaScript
- JavaScript is the free language built into all modern browsers including Internet Explorer, Firefox, Safari, Opera and Chrome. It is the power behind dynamic HTML and the Ajax environment used for Web 2.0 websites such as Facebook, Flickr, Gmail, and many others.
- Unlike other languages used for creating websites such as Perl, PHP, and Ruby, JavaScript runs within the web browser and not on a web server. This means it can modify HTML elements in real time. It's also the technology behind Web 2.0 Ajax functionality, in which data is transferred between a web server and web browser behind the scenes.
- JavaScript's great power lies in its ability to access HTML's Document Object Model (DOM).
Incorporating JavaScript into a web page
- JavaScript code is generally embedded within a web page to which it applies. This can be in the form of the direct code itself or by means of a tag that tells the browser the location of a file containing some JavaScript to load in and execute.
- The location within a web page at which you insert the JavaScript (or link to a JavaScript file) is the default location in which any output from the JavaScript will be inserted.
Comments
- Comments let you annotate your code for yourself and others. You can also use comments to temporarily disable blocks of code.
- There are two ways to create a comment in JavaScript.
- Preface it with two slashes, e.g.:
// This is a comment
anumber = 42 // Assigns 42 to anumber
- The multi-line form of comment starts with /* and ends with */, e.g.:
/* This is a multiline set of comments, which can appear over any number of lines */
- Preface it with two slashes, e.g.:
Using semicolons
- Many programmers add a semicolon after every JavaScript statement but this isn't mandatory.
- If you place more than one statement on a single line, you must separate them with a semicolon. Think of the semicolon as acting as a new line as far as the JavaScript interpreter is concerned.
Where to place the JavaScript code
- In the document head. Place the JavaScript within
<script>
tags. - In the document body. Place the JavaScript within
<script>
tags. - In separate JavaScript files. JavaScript files typically have an extension of .js. Link to them in the document head or body with code like this:
- Same directory:
<script src='myscript.js'></script>
- Different directory:
<script src=
'pathtofolder/ myscript.js> </script> - Different server:
<script src='http://server.com/
folder/ script.js'> </script>
- Same directory:
JavaScript syntax
Syntax is a set of rules that define how to correctly structure a JavaScript program.
Case sensitivity
- JavaScript is case sensitive.
- Best practices for naming:
- Global variables accessible anywhere in a program are uppercase, e.g.
HIGHSCORE
. - Temporary variables used in loops are single letters and lowercase, e.g.,
j
. - Function names use a capital letter at the start of each word, e.g.,
MyFunctionName()
.
- Global variables accessible anywhere in a program are uppercase, e.g.
Whitespace
- Spaces and tabs are known as whitespace and any combination of these is usually treated by JavaScript as if it were a single space. The exception is when they are placed inside quotation marks, in which case they form part of a string.
- Newline or carriage return characters are also treated as whitespace within JavaScript (unless within quotes), except that each one creates an implied semicolon, which is used to denote a statement.
Variables
- A variable in any programming language is simply a container for a value.
- When a variable is used to store a number, it's known as a numeric variable. Examples:
MyVariable = 42
MyVariable = MyVariable + 13 // = 55
MyVariable = MyVariable * 3 // = 165
- When a variable is used to store text, it's known as a string variable. The quotation marks tell JavaScript that the value is a string. Examples:
- Singer = "Paul" // = Paul
- Singer = Singer + " Simon" // = Paul Simon
The second example demonstrates how you can concatenate two strings together, that is, attach one to the other.
Variable naming
- Variables must begin with either an upper or lower case letter (a-z or A-Z), or the $ or _ characters.
- Variable names may not container any mathematical operators (such as + or *), punctuation (such as ! or &), or spaces.
- After the first character, variable names may include the digits 0-9.
- All JavaScript keywords (such as
window
,open
, andstring
) may not be used as variable names.
Using quotation marks in strings
- You may use either a double quote or a single quote to indicate the start and end of a string. Examples:
Dinner = "Fish and Chips"
Dinner = 'Fish and Chips
'
- If you need to include a particular quotation mark within a string, switch to the other quote option, e.g., if there's a single quote in the strong, use double quotes to enclose the string. Examples:
ChatComment = "Isn't the weather fine?"
QuoteComment = 'She said "No."
'
- See escape characters for instances when you may need to enclose both single and double quotes.
- Placing a pair of quotes together with nothing between them results in what's called an empty string. It is commonly used for erasing or initializing the value of a string variable. Example:
ChatComment = ""
ChatComment = ''
Escape characters
- The escape character is a backslash (\). The escape character tells JavaScript to ignore the \ character and to use the character following it as a string element and not a string container.
- Example with both single and double apostrophes:
ChatComment = "Mark said, \"I can't wait.\""
- Common escape characters:
- \' — single quote
- \" — double quote
- \\ — backslash
- \b — backspace
- \f — form feed
- \n — new line
- \r — carriage return
- \t — tab
Variable typing and casting
- JavaScript employs automatic type casting, in which a variable can change its type automatically. For example, a string can become a number, and vice versa, depending on how it's referenced.
- Example:
MyVar = "12345" // quotes make it a string variable
MyVar = MyVar - 345 // = 12000 due to automatic type conversion
- Example:
Time = 6 //numeric variable
Time = Time + " o'clock" // = 6 o'clock due to automatic type conversion
- Example:
- There are times when you must force the type of a variable, most often when you are processing user input and have less control over the values. For instance:
MyVar = "12345" + 678 // = "12345678", not 13023
. To force this to be a number, use the functionNumber()
like this:MyVar = Number("12345") + 678
- However using an operand can force a string to become a number:
s = '12345' * 1 + 54321 // String cast to a number with * 1 and a number
- Forcing the type of a variable is known as casting. There are three functions available for this:
- Boolean(): Cast the value to either true or false.
- Any string of at least one character in length, any object, or any number greater than 0 will be cast to the value
true
. - Empty strings, the number 0, and the values
undefined
ornull
result in the valuefalse
.
- Any string of at least one character in length, any object, or any number greater than 0 will be cast to the value
- Number(): Cast the value to a number. If the value is a string containing characters other than digits, or can't be converted to a number for another reason, than the JavaScript value
NaN
(for Not a Number) will be returned. SinceNaN
values cannot have arithmetic operations performed on them, any attempt to do so will see the value remain asNaN
. - String(): Cast the value to a string. The
string()
function can safely turn any value into a string, including JavaScript values such asNaN
,null
,undefined
,true
, andfalse
.
- Boolean(): Cast the value to either true or false.
JavaScript operators
Arithmetic operators
Operator | Description | Example | Result |
---|---|---|---|
+ |
Addition | 3 + 11 |
141 |
- |
Subtraction | 9 - 4 |
5 |
* |
Multiplication | 3 * 4 |
12 |
/ |
Division | 21 / 7 |
3 |
% |
Modulus (remainder after division) | 21 % 8 |
5 |
++ |
Increment (increase by 1). In preincrementing (the ++ is before the variable, e.g., ++a ), the variable is incremented before it is used. In postincrementing (the ++ is after the variable, e.g., a++ ), the variable is incremented after it is used. |
a = 5; ++a |
(a equals) 6 |
-- |
Decrement (decrease by 1). This can be preincremented (--a ) or postincremented (a-- ). |
a = 5; --a |
(a equals) 4 |
Arithmetic functions
Function | Description |
---|---|
Math.abs(a) |
Returns a as a positive number (absolute value). |
Math.acos(a) |
Returns the arc cosine of a . |
Math.asin(a) |
Returns the arc sine of a . |
Math.atan(a) |
Returns the arc tangent of a . |
Math.atan2(a,b) |
Returns the arc tangent of a / b . |
Math.ceil(a) |
Rounds up to return the integer closest to a . |
Math.cos(a) |
Returns the cosine of a . |
Math.exp(a) |
Returns the exponent of a (Math.E to the power a ). |
Math.floor(a) |
Rounds down to return the integer closest to a . |
Math.log(a) |
Returns the log of a base e . |
Math.max(a,b) |
Returns the maximum of a and b . |
Math.min(a,b) |
Returns the minimum of a and b . |
Math.pow(a,b) |
Returns a to the power b . |
Math.random() |
Returns a random number between 0 and 0.999 (recurring). Example — to emulate a 6-sided dice: Math.ceil(Math.random() * 6) // returns 1-6 |
Math.round(a) |
Rounds up or down to return the integer closest to a . |
Math.sin(a) |
Returns the sine of a . |
Math.sqrt(a) |
Returns the square root of a . |
Math.tan(a) |
Returns the tangent of a . |
Assignment operators
Note: Variable a
already contains the value 21.
Operator | Description | Example | Result |
---|---|---|---|
= |
Simple assignment | a = 42 |
42 |
+= |
With addition | a += 5 |
26 |
-= |
With subtraction | a -= 2 |
19 |
*= |
With multiplication | a *= 3 |
63 |
/= |
With division | a /= 10 |
2.1 |
%= |
With modulus | a %=4 |
1 |
Comparison operators
Operator | Description | Example | Result |
---|---|---|---|
== |
Equal to | 1 == 1 |
true |
=== |
Equal in value and type | 1 === '1' |
false |
!= |
Not equal to | 1 != 2 |
true |
!== |
Not equal in value & type | 1 !== '1' |
true |
> |
Greater than | 1 > 2 |
false |
< |
Less than | 1 < 2 |
true |
>= |
Greater than or equal to | 1 >= 1 |
true |
<= |
Less than or equal to | 2 <=1 |
false |
Logical operators
Operator | Description | Example | Result |
---|---|---|---|
&& |
And (&& is known as the and operator) |
1 == 1 && 2 == 2 |
true |
|| |
Or (|| is known as the or operator) |
1 == 1 || 2 ++ 3 |
true |
! |
Not (! is known as the not operator) |
!(1 == 1) |
false |
The ternary operator
- The ternary operator allows you to combine "If this then do that thing otherwise do another thing" logic into a single expression.
- You provide an expression that can return either
true
orfalse
(a Boolean expression) and follow it with a?
character. - Then you place the two options, separated with a : character.
- Ternary syntax:
expression ? do this if true : do that if false
- You provide an expression that can return either
- Example 1:
document.write(game == over ?
'Game over' : 'Keep playing')
- Example 2:
AmPm = Time < 12 ? 'AM' : 'PM'
Bitwise operators
Bitwise operators act on the individual 0 and 1 bits that make up binary numbers. Only very advanced JavaScript coders should use these.
Operator | Description |
---|---|
& |
Bitwise and |
| |
Bitwise or |
^ |
Bitwise exclusive or |
~ |
Not |
<< |
Left-shift |
>> |
Right-shift |
>>> |
Zero-fill right-shift |
Operator precedence
- In JavaScript, some operators are given a higher precedence than others. For example, multiplication has a higher precedence than addition, so in the following expression the multiplication will occur before the addition, even though the addition appears first: 3 + 4 * 5.
- The table below shows operator precedence.
Precedence Operator type Associativity Individual operators 1 member left-to-right . [] new right-to-left new 2 function call left-to-right () 3 increment n/a ++ decrement n/a -- 4 logical-not right-to-left ! bitwise not right-to-left ~ unary + (used before an expression to force it to be a number) right-to-left + unary negation (used before an expression to negate it, i.e., change negative value to positive or vice versa) right-to-left - typeof right-to-left typeof void right-to-left void delete right-to-left delete 5 multiplication left-to-right * division left-to-right / modulus left-to-right % 6 addition left-to-right + subtraction left-to-right - 7 bitwise shift left-to-right << >> >>> 8 relational left-to-right < <= > >= in left-to-right in instanceof left-to-right instanceof 9 equality left-to-right == != === !== 10 bitwise-and left-to-right & 11 bitwise-xor left-to-right ^ 12 bitwise-or left-to-right | 13 logical-and left-to-right && 14 logical-or left-to-right || 15 conditional right-to-left ?: 16 assignment right-to-left = += -= *= /= %= <<= >>= >>>= &= ^= |= 17 comma left-to-right ,
The with statement
- The
with
statement lets you simplify some types of JavaScript statements by reducing many references to an object to a single reference.- Example: in the following code, the
document.write()
function never references the variablestring
by name.string = "The quick brown fox jumps over the lazy dog"
with (string)
{document.write("The string's length is " + length)
doucment.write("<br />Upper case: " + toUpperCase())}
- Example: in the following code, the
- This works because the JavaScript interpreter recognizes that the
length
property and thetoUppercase()
method have to applied to some object but, because they standalone, the interpreter assumes they must apply to thestring
object specified in thewith
statement. - Caveat: This can appear ambiguous. Use this technique only when it's clear what you're doing.
JavaScript arrays
- Access each elementin an array numerically, starting with element 0.
- JavaScript arrays can be any size up to the availble memory in your computer.
Array names
- The naming rules for arrays are the same as for variables.
- Array names must begin with either an uppercase or lowercase letter or the $ or _ symbols.
- Array names may not contain any mathematical operators (such as + or *), punctuation (such as ! or &), or spaces.
- After the first character, array names may include the digits 0-9 as well as any character that can be the first character.
- All JavaScript keywords (such as window, open, string, and so on) are reserved and may not be used as array names.
Creating an array
- You can create an array by declaring it in advance to initialize it, like this:
MyArray = new Array()
- This creates a new object of the type
Array()
and then assigns the nameMyArray
to it.
- This creates a new object of the type
- To create an array of a specific length, provide a single argumentto the Array() function call, e.g.:
MyArray = new Array(5)
. This array has no data but has five elements ready to be populated with values. - See also: Other ways of creating arrays
Assigning values to an array element
- Populating arrays with data is like assigning values to variables.
- Examples:
MyArray[0] = 23
"
MyArray[1] = 67.35
MyArray[3] = "Hello world"
MyArray[4] = new Date() // a date object holding the current date and time
MyArray[2] = "Goodmorning
- Examples:
Using indexes
- The element number used for storing a particular value is known as the array index.
- As shown above, you can use integer values as indexes.
- You can also use integer variable values, e.g., 123. In the example below, a variable with a numerica value is created and is then used to assign another value to the array.
- Example:
MyIndex = 123
MyArray[MyIndex] = "Good evening"
- Example:
Returning values
- To return a value from an array, you simply refer to it.
- Example 1:
document.write(MyArray[0])
.This will fetch the value stored in the element occupying the first position of
MyArray[]
. - Example 2:
MyIndex = 713
document.write(MyArray[MyIndex])This will fetch whatever value is stored in element 713 of
MyArray[]
.
- Example 1:
- If you try to read from an array that hasn't been previously created, an error will be generated and your code will fail.
- Other ways you can use array values include assigning them to other variables or other array elements and using them in expressions.
- Example 1:
MyArray[7] = 23
document.write(MyArray[7] + 50) - Example 2 (creates an alert box):
MyArray[7] = 23
alert(MyArray[7] + 50)
- Example 1:
Using array elements as indexes
- You can use the value stored in an array element as an index into another, or the same array.
- Example:
OtherArray[0] = 77
MyArray[OtherArray[0] = "I love the movie Inception"Here the zeroth element of
OtherArray[]
is assigned the integer value of 77. Once assigned, this element is used as the index intoMyArray[]
.
- Example:
- You can use mathematical equations to iterate through arrays. For example, it is easy to create code that runs in a loop to process each element of an array in turn.
Other ways of creating arrays
- In addition to a simple declaration of a new array, e.g.,
MyArray = new Array()
, there are other methods that allow you to populate the array with some data at the same time- Example 1:
MyArray = new Array(123, "Hello there", 3.21)
- Example 2:
MyArray = [123, "Hello there", 3.21]
- Example 1:
- Once yu have created an array, if you need to apply any more values to elements within it, you must use the standard form of assigning values, e.g.,
MyArray[0] = 1234
. If you reuse the short form of combined array creation and value assignment, it will simply reset the array to the values in the assignment.
Using associative arrays
- Once an array starts to hold meaningful amounts of data, using numbers to access its elements can be confusing. Instead, you can use an associative array where you can use names to associate with array elements in much the same way that variables have names.
- Example 1:
SoccerTeam = new Array()
SoccerTeam['Andy'] = 10
SoccerTeam['Brian'] = 8
SoccerTeam['Cathy'] = 9
SoccerTeam['David'] = 10
SoccerTeam['Ellen'] = 9These values can be looked up by name, like this:
document.write(SoccerTeam['Cathy'])
These values can be looked up by name, like this:
document.write(SoccerTeam['Cathy'])
- Example 2:
SoccerTeam = new Array(
{SoccerTeam['Andy'] : 10
SoccerTeam['Brian'] : 8
SoccerTeam['Cathy'] : 9
SoccerTeam['David'] : 10
SoccerTeam['Ellen'] ; 9})
Note the addition of curly brackets and the use of colons instead of equal signs in this example.
You can assign any valid value, including integers, floating point numbers, strings, and even other arrays and objects into an associative array.
MyInfo =
{
'Name' : Bill Gates,
'Age' : 56,
'Occupation' : Philanthropist,
'Children' : 3,
'Worth' : 59000000000}
You can read back any value by referring to it, e.g.:
document.write(MyInfo['Occupation'])
- Example 3:
SoccerTeam =
{'Andy' : 10,
'Brian' : 8,
'Cathy' : 9,
'David' : 10,
'Ellen' : 9}
- Example 1:
- When you use associative arrays, you are actually creating a collection of key and value pairs. The name you assign to an array element is known as the key; the value you provide to the element is the value.
- In other languages, such as PHP, the collection of key and value pairs would be known as a hash table and each key would be known as a hash value.
Manipulating arrays
- Use
push
to add a new element to the bottom of an array.- Example:
FoodArray.push('egg')
In this example, the index will automatically be updated with the next number in the sequence.
- Example:
- Use
pop
to remove the last element from an array.- Example:
FoodArray.pop()
- Example:
- Use
reverse
to display an array in reverse order.- Example:
document.write(DrinkArray.reverse()
- Example:
- Use
sort
to display an array in order.- Example:
document.write(DrinkArray.sort()
- Example:
- Use
splice
to remove and add multiple elements.- Example:
PetArray.splice(2, 1, 'rabbit', 'hamster')
This removes 1 element with index position 2 and adds two new elements.
- Example:
Multidimensional arrays
- While there's actually no such thing as multidimensional arrays in JavaScript, you can simulate them by assigning new arrays as the values for elements of an existing array. The arrays we've dealt with so far are one-dimensional arrays which equate to a simple list. A two-dimensional array is similar to a table, or matrix, with columns and rows. The number of indices needed to specify an element is called the dimension, dimensionality, or rank of the array type. You can continue adding arrays within other arrays until you run out of computer memory.
Creating a two-dimensional array
- An example of a two-dimensional array is a simple multiplication table.
1 2 3 4 5 6 7 8 9 10 1 1 2 3 4 5 6 7 8 9 10 2 2 4 6 8 10 12 14 16 18 20 3 3 6 9 12 15 18 21 24 27 30 4 4 8 12 16 20 24 28 32 36 40 5 5 10 15 20 25 30 35 40 45 50 6 6 12 18 24 30 36 42 48 54 60 7 7 14 21 28 35 42 49 56 63 70 8 8 16 24 32 40 48 56 64 72 80 9 9 18 27 36 45 54 63 72 81 90 10 10 20 30 40 50 60 70 80 90 100 Each of the columns (or each of the rows) can be considered a one-dimensional array. For example, the first column could be created using the following code:
MyTable0 = new Array()
MyTable0[0] = 1
MyTable0[1] = 2
MyTable0[2] = 3
MyTable0[3] = 4
MyTable0[4] = 5
MyTable0[5] = 6
MyTable0[6] = 7
MyTable0[7] = 8
MyTable0[8] = 9
MyTable0[9] = 10
Or, more succinctly,
MyTable0 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
. If you create an array for each column or row using this technique, e.g., myTable1[], myTable 2[] ... myTable, you are one step aray from being able to build a two-dimensional table. - Using a master table referencing one-dimensional array, you can create a two-dimensional table. Example:
masterTable = [My Table0, My Table1, My Table2, My Table3, My Table4, My Table5, My Table6, My Table7, My Table8, My Table9]
.
Accessing a two-dimensional array
- To access a two-dimensional array, you add another pair of square brackets following the first pair, and place an indic value into that new array between them, e,g.,
alert(MasterTable[0][0])
to display the first element of the array that is stored in the first element ofMasterTable[]
. There is no need to reference the subarray by name. (Subarray refers to arrays within arrays.) To display the value held in the seventh row of the array stored in the third element of MasterTable[] you could code it asalert(MasterTable[2][6]).
Multidimensional associative arrays
- As with numeric arrays, you can create multidimensional associative arrays.
JavaScript array functions
- JavaScript functions for accessing and manipulating arrays allow you to join arrays together, push new items into an array and pop them off again, reverse the data in an array, sort it alphabetically or numerically, and more.
Using for (... in ...)
- for (... in ...) lets you iterate through an array one element at a time.
- Simple array used in example:
Cats = ['Long Hair', 'Short Hair', 'Dwarf', 'Farm', "Tabby', 'Tortoiseshell']
- Example, display all items in array:
for (index in Cats) {
document.write(Cats[index] + '<br />')
}
The for() keyword creates a new variable called index, which it initializes with the integer value of 0, so it points to the first element in the specified array. Then the contents of the curly brackets are executed once for each element in the array, with index being incremented each time around.
- Note: the index variable
i
can be used instead ofindex
. - Note: If there is only one statement in the curly brackets, the curly brackets can be omitted. Example:
for (i in Cats) document.write(Cats[i] + '<r />')
- Simple array used in example:
- See the using forEach() section for an alternative to using for (... in ...).
Using concat
- Using the
concat()
function, you can return a new array created by joining two other arrays together. The original arrays are not changed.- Example of creating a new array called
Pets[]
from arrays namedCats[]
andDogs[]
.Pets = Cats.concat(Dogs)
- Example if you want the contents of Dog[] before Cats[]:
Pets = Dogs.concat(Cats)
- You can omit the creation of the
Pets[]
array and simply iterate through the result of theconcat()
call like this:for (i in Dogs.concat(Cats))
document.write(Dogs.concat(Cats)[i] + '<br />')
Note: This is not a recommended approach since the concatenation has to be done twice.
- Example of creating a new array called
Alternative to concat()
- If all you want to do is to quickly see what values are in an array, you can use the implied concatenation you get when referencing an array as an argument to the document.write() function.
- For example, you can list all the elements in the Dogs[] array to the browser (seperated with commas) like this:
document.write(Dogs)
Note that you must omit the [] characters from after they array name for this to work. The result of this statement will be something like this:
Pit Bull,Spaniel,Terrier,Beagle,Shepherd
- For example, you can list all the elements in the Dogs[] array to the browser (seperated with commas) like this:
Using join()
- If you want to turn all the elements in an array into a string, use the
join(0
) function.- Example:
document.write(Cats.join(' and '))
- This calls the join() function, passing it the string ' and ', which is used as a separator, which is inserted between each element. The result might look like:
Long Hair and Short Hair and Dwarf and Farm
- Note: when no argument is passed to join (the contents in the parentheses), a comma is asumed as the separator. To have no separator, pass an empty string, e.g.,
('')
.
- This calls the join() function, passing it the string ' and ', which is used as a separator, which is inserted between each element. The result might look like:
- Example:
Using forEach()
- The
forEach() function
is an alternative to usingfor (... in ...)
. With it, you can iterate through an array of elements very easily, as follows. (Thev
in the arguments of theinfo()
fuction is the index of the element anda
is the array contents.)- Example:
Dogs = [ 'Pit Bull', 'Spaniel', 'Terrier', 'Beagle', 'Shepherd', 'Bulldog' ]
Dogs.forEach(info)
function info(v, i, a) {
document.write('[' + i + '] is ' + v + '<br />');
}
This returns
[0] is Pit Bull
,[1] is Spaniel
, etc.
- Example: