JavaScript Introduction
JavaScript Introduction
1|P a ge
1. JavaScript Introduction
JavaScript Where To
1|P a ge
In HTML, JavaScripts must be inserted between <script> and </script> tags.
JavaScripts can be put in the <body> and in the <head> section of an HTML page.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
Draft Copy 2 | P a g e
</body>
</html>
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
It is a good idea to place scripts at the bottom of the <body> element.
This improves page load, because HTML loading is not blocked by scripts loading.
External JavaScripts
Scripts can also be placed in external files.
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the source (src) attribute of the
<script> tag:
Example
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
You can place an external script reference in <head> or <body> as you like.
The script will behave as if it was located exactly where you put the reference in the HTML
document.
External scripts cannot contain <script> tags.
JavaScript Output
Draft Copy 4 | P a g e
If your browser supports debugging, you can use the console.log() method to display JavaScript
values.
Activate debugging in your browser with F12, and select "Console" in the debugger menu.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
</body>
</html>
2. JavaScript Syntax
JavaScript Syntax
JavaScript is a scripting language. A scripting language is a lightweight programming
language.
The sentences in a programming language are called statements.
The principles, how sentences are constructed in a language, are called language syntax.
JavaScript Literals
In a programming language, a literal is a constant value, like 3.14.
Number literals can be written with or without decimals, and with or without scientific
notation (e):
3.14
1001
123e5
String literals can be written with double or single quotes:
"John Doe"
'John Doe'
Expression literals evaluate (compute) to values:
5+6
5 * 10
Array literals defines an array:
[40, 100, 1, 5, 25, 10]
Object literals defines an object:
{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}
Function literals defines a function:
function myFunction(a, b) { return a * b;}
JavaScript Variables
In a programming language (and in algebra), variables are used to store data values.
Draft Copy 5 | P a g e
JavaScript uses the var keyword to define variables.
An equal sign is used to assign values to variables (just like algebra).
In this example, length is defined as a variable. Then, it is assigned (given) the value 6:
var length;
length = 6;
A literal is a fixed value. A variable is a name that can have variable values.
JavaScript Operators
JavaScript uses arithmetic operators to compute values (just like algebra):
(5 + 6) * 10
JavaScript uses an assignment operator to assign values to variables (just like algebra):
x = 5;
y = 6;
z = (x + y) * 10;
The JavaScript language has many types of operators:
Type Examples Description
Assignment, arithmetic, and bitwise operators = + - * / Described in JS Operators
Conditional, comparison, and logical operators == != < > Described in JS Comparisons
JavaScript Statements
A computer program is a sequences of "executable commands" called statements.
JavaScript statements are separated by semicolon:
x = 5 + 6;
y = x * 10;
Multiple statements on one line is allowed:
x = 5 + 6; y = x * 10;
JavaScript Keywords
A JavaScript statement often starts with a keyword.
The var keyword tells the browser to create a new variable:
var x = 5 + 6;
var y = x * 10;
JavaScript Identifiers
All programming languages must identify all variables with unique names.
These unique names are called identifiers.
Identifiers can contain letters, digits, underscores, and dollar signs, but cannot begin with a
number.
Reserved words (like JavaScript keywords) cannot be used as identifiers.
JavaScript Comments
Not all JavaScript statements are "executable commands".
Anything after double slashes // is treated as a comment, ignored, and not executed:
// x = 5 + 6; Will not be executed
Draft Copy 6 | P a g e
var lastName = "Johnson"; // String assigned by a string literal
var cars = ["Saab", "Volvo", "BMW"]; // Array assigned by an array literal
var x = {firstName:"John", lastName:"Doe"}; // Object assigned by an object literal
JavaScript Functions
JavaScript statements written inside a function, can be invoked and reused many times.
Invoke a function = call a function (ask for the code in the function to be executed).
function myFunction(a, b)
{
return a * b; // return the product of a and b
}
3. JavaScript Statements
In HTML, JavaScript statements are "command lines" executed by the web browser.
JavaScript Statements
In HTML, JavaScript statements are "commands" to the browser.
The purpose, of the statements, is to tell the browser what to do.
This statement tells the browser to write "Hello Dolly" inside an HTML element identified with
id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
JavaScript Code
JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
Each statement is executed by the browser in the sequence they are written.
Draft Copy 7 | P a g e
This example will manipulate two different HTML elements:
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
document.getElementById("myDiv").innerHTML = "How are you?";
Semicolon;
Semicolon separates JavaScript statements.
Normally you add a semicolon at the end of each executable statement:
a = 5;
b = 6;
c = a + b;
Multiple statements on one line is allowed:
a = 5; b = 6; c = a + b;
You might see examples without semicolons.
Ending statements with semicolon is optional in JavaScript.
Draft Copy 8 | P a g e
switch Marks a block of statements to be executed, depending on different cases
throw Throws (generates) an error
try Implements error handling to a block of statements
var Declares a variable
while Marks a block of statements to be executed, while a condition is true
document.getElementById("demo").innerHTML = \
"Hello Dolly!";
JavaScript Comments
JavaScript comments can be used to explain the code, and make the code more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.
Draft Copy 9 | P a g e
var x = 5; // Declare x, give it the value of 5
var y = x + 2; // Declare y, give it the value of x + 2
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
The following example uses a multi-line comment (a comment block) to explain the code:
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
It is most common to use single line comments.
Block comments are often used for formal documentation.
The following example uses a comment block to prevent execution of multiple lines:
Example
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/
4. JavaScript Variables
Draft Copy 10 | P a g e
In algebra we use letters (like x) to hold values (like 5).
From the expression z = x + y above, we can calculate the value of z to be 11.
In JavaScript these letters are called variables.
JavaScript variables are containers for storing values.
JavaScript Variables
As with algebra, JavaScript variables can be used to hold values (x = 5) or expressions (z = x +
y).
Variable can have short names (like x and y) or more descriptive names (age, sum,
totalVolume).
Variable names can contain letters, digits, underscores, and dollar signs.
o Variable names must begin with a letter
o Variable names can also begin with $ and _ (but we will not use it)
o Variable names are case sensitive (y and Y are different variables)
o Reserved words (like JavaScript keywords) cannot be used as variable names
Draft Copy 11 | P a g e
Then we "output" the value inside an HTML paragraph with id="demo":
Example
<p id="demo"></p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
It's a good programming practice to declare all variables at the beginning of a script.
Value = undefined
In computer programs, variables are often declared without a value. The value can be something
that has to be calculated, or something that will be provided later, like user input. Variable
declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of the following
statement:
var carName;
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:
Example
var y = 5;
var x = y + 2;
You can also add strings, but strings will be concatenated (added end-to-end):
Example
var y = "5";
var x = y + 2;
Draft Copy 12 | P a g e
Note that if you add a number to a string, both will be treated as strings.
You will learn a lot more about arithmetic operators later in this tutorial
5. JavaScript Data Types
JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
Example
var carName = "Volvo XC60"; // Using double quotes
var carName = 'Volvo XC60'; // Using single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the
string:
Example
var answer = "It's alright"; // Single quote inside double quotes
var answer = "He is called 'Johnny'"; // Single quotes inside double quotes
var answer = 'He is called "Johnny"'; // Double quotes inside single quotes
You will learn a lot more about strings later in this tutorial.
JavaScript Numbers
JavaScript has only one type of numbers.
Numbers can be written with, or without decimals:
Example
var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals
Extra large or extra small numbers can be written with scientific (exponential) notation:
Example
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
You will learn a lot more about numbers in the advanced section of this tutorial.
JavaScript Booleans
Booleans can only have two values: true or false.
var x = true;
var y = false;
Booleans are often used in conditional testing.
You will learn a lot more about conditional testing later in this tutorial.
JavaScript Arrays
JavaScript arrays are written with square brackets.
Array items are separated by commas.
Draft Copy 13 | P a g e
The following code declares (creates) an array called cars, containing three items (car names):
Example
var cars = ["Saab", "Volvo", "BMW"];
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
You will learn a lot more about arrays later in this tutorial.
JavaScript Objects
JavaScript objects are written with curly braces.
Object properties are written as name:value pairs, separated by commas.
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
The object (person) in the example above has 4 properties: firstName, lastName, age, and
eyeColor.
You will learn a lot more about objects later in this tutorial.
In JavaScript, an array is a special type of object. Therefore typeof [1,2,3,4] returns object.
6. JavaScript Objects
JavaScript objects are containers for variables called properties and methods.
Draft Copy 14 | P a g e
A car has properties like weight and color, and methods like start and stop:
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
JavaScript Objects
In JavaScript, almost "everything" is an object.
In JavaScript, objects are king. When you understand objects, you will understand JavaScript.
You have already learned that JavaScript variables are containers for data values.
This code assigns the value "Fiat" to a variable named car:
var car = "Fiat";
Objects are variables too. But objects can contain many values (many variables).
var car {type:"Fiat", model:500, color:"white"};
In the example above, 3 values ("Fiat", 500, "white") are assigned to the variable named car.
In the example above, 3 variables (type, model, color) are assigned to the variable named car:
JavaScript objects are containers for variables.
Object Definition
With an object literal, you define and create a JavaScript object:
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Spaces and line breaks are not important. An object definition can span multiple lines:
Example
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Object Properties
It is ok to say: "JavaScript objects are containers for variables".
But, it is more common to say: "JavaScript objects are containers for named values.
Named values are written as name : value pairs (name and value separated by a colon).
The name value pairs, in JavaScript objects, are called object properties.
JavaScript objects are containers for variables called properties.
Objects written as name value pairs are similar to:
Associative arrays in PHP
Dictionaries in Python
Hash tables in C
Hash maps in Java
Hashes in Ruby and Perl
Draft Copy 15 | P a g e
Accessing Object Properties
You can access object properties in two ways:
Example1
person.lastName;
Example2
person["lastName"];
Object Methods
An object method is a function definition stored as an object property.
It will execute (as a function) when it is invoked with ().
This example access the fullName() method of a person object:
Example
name = person.fullName();
If you access the fullName property of the person object, it will return the function definition:
Example
name = person.fullName;
JavaScript objects are containers for variables called properties and methods.
You will learn much more about functions, properties, and methods, later in this tutorial.
Example
function myFunction(p1, p2) {
return p1 * p2; // the function returns the product of p1 and p2
}
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
You will learn a lot more about function invocation later in this tutorial.
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after
the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
Example
Calculate the product of two numbers, and return the result:
var x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
The result in x will be:
12
Why Functions?
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.
Example
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
Draft Copy 17 | P a g e
You can use:
text = "The temperature is " + toCelsius(32) + " Centigrade";
JavaScript functions can be redefined like ordinary variables.
JavaScript functions can also be passed as values to other functions.
You will learn a lot more about functions later in this tutorial.
8. JavaScript Scope
Scope is the set of variables you have access to.
JavaScript Scope
In JavaScript, objects and functions, are also variables.
In JavaScript, scope is the set of variables, objects, and functions you have access to.
JavaScript has function scope: The scope changes inside functions.
Automatically Global
If you assign a value to a variable that has not been declared, it will automatically become a
GLOBAL variable.
This code example will declare carName as a global variable, even if it is executed inside a
function.
Example
// code here can use carName
function myFunction() {
carName = "Volvo";
// code here can use carName
}
Function Arguments
Function arguments (parameters) work as local variables inside functions.
HTML Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
o An HTML web page has finished loading
o An HTML input field was changed
o An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
With single quotes:
<some-HTML-element some-event='some JavaScript'>
With double quotes:
<some-HTML-element some-event="some JavaScript">
In the following example, an onclick attribute (with code), is added to a button element:
Example
<button onclick='getElementById("demo").innerHTML=Date()'>The time is?</button>
In the example above, the JavaScript code changes the content of the element with id="demo".
In the next example, the code changes the content of it's own element (using this.innerHTML):
Example
<button onclick="this.innerHTML=Date()">The time is?</button>
JavaScript code is often several lines long. It is more common to see event attributes calling
functions:
Example
<button onclick="displayDate()">The time is?</button>
You will learn a lot more about events and event handlers in the HTML DOM chapters.
JavaScript Strings
A JavaScript string simply stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use single or double quotes:
Example
var carname = "Volvo XC60";
var carname = 'Volvo XC60';
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
Or you can put quotes inside a string by using the \ escape character:
Example
var answer = 'It\'s alright';
var answer = "He is called \"Johnny\""
String Length
The length of a string (a string object) is found in the built in property length:
Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Special Characters
In JavaScript, strings are written as characters inside single or double quotes.
Draft Copy 20 | P a g e
Because of this, JavaScript will misunderstand this string:
"We are the so-called "Vikings" from the north."
The string will be chopped to "We are the so-called ".
To solve this problem, you can place a backslash (\) before the double quotes in "Vikings":
"We are the so-called \"Vikings\" from the north."
The backslash is an escape character. Escape characters turns special characters into string
characters:
The escape character (\) can be used to insert apostrophes, new lines, quotes, and other special
characters into a string.
The table below lists other special characters that can be added to a text string with the
backslash sign:
Code Outputs
\' single quote
\" double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
Example
var x = "John";
var y = new String("John");
// (x === y) is now false because x is a string and y is an object.
String Properties
Property Description
constructor Returns the function that created the String object's prototype
length Returns the length of a string
prototype Allows you to add properties and methods to an object
String Methods
Method Description
charAt() Returns the character at the specified index (position)
Draft Copy 21 | P a g e
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a copy of the joined strings
fromCharCode() Converts Unicode values to characters
indexOf() Returns the position of the first found occurrence of a specified value in a
string
lastIndexOf() Returns the position of the last found occurrence of a specified value in a
string
localeCompare() Compares two strings in the current locale
match() Searches a string for a match against a regular expression, and returns the
matches
replace() Searches a string for a value and returns a new string with the value replaced
search() Searches a string for a value and returns the position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
substr() Extracts a part of a string from a start position through a number of characters
substring() Extracts a part of a string between two specified positions
toLocaleLowerCase() Converts a string to lowercase letters, according to the host's locale
toLocaleUpperCase() Converts a string to uppercase letters, according to the host's locale
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a string
valueOf() Returns the primitive value of a String object
11. JavaScript String Methods
String methods help you to work with strings.
Draft Copy 23 | P a g e
Banana
If the first parameter is negative, the position counts from the end of the string.
The second parameter can not be negative, because it defines the length.
If you omit the second parameter, substr() will slice out the rest of the string.
JavaScript Numbers
JavaScript numbers can be written with, or without decimals:
Example
var x = 34.00; // A number with decimals
var y = 34; // A number without decimals
Extra large or extra small numbers can be written with scientific (exponent) notation:
Example
var x = 123e5; // 12300000
var y = 123e-5; // 0.00123
Precision
Integers (numbers without a period or exponent notation) are considered accurate up to 15
digits.
Example
var x = 999999999999999; // x will be 999999999999999
var y = 9999999999999999; // y will be 10000000000000000
Draft Copy 25 | P a g e
The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:
Example
var x = 0.2 + 0.1; // x will be 0.30000000000000004
To solve the problem above, it helps to multiply and divide:
Example
var x = (0.2 * 10 + 0.1 * 10) / 10; // x will be 0.3
Hexadecimal
JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.
Example
var x = 0xFF; // x will be 255
Never write a number with a leading zero (like 07).
Some JavaScript versions interpret numbers as octal if they are written with a leading zero. By
default, Javascript displays numbers as base 10 decimals.
But you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or
base 2 (binary).
Example
var myNumber = 128;
myNumber.toString(16); // returns 80
myNumber.toString(8); // returns 200
myNumber.toString(2); // returns 10000000
Infinity
Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the
largest possible number.
Example
var myNumber = 2;
while (myNumber != Infinity) { // Execute until Infinity
myNumber = myNumber * myNumber;
}
Division by 0 (zero) also generates Infinity:
Example
var x = 2 / 0; // x will be Infinity
var y = -2 / 0; // y will be -Infinity
Infinity is a number: typeOf Infinity returns number.
Example
typeof Infinity; // returns "number"
Draft Copy 26 | P a g e
var x = NaN;
var y = 5;
var z = x + y; // z will be NaN
NaN is a number: typeOf NaN returns number.
Example
typeof NaN; // returns "number"
Don't create Number objects. They slow down execution speed, and produce nasty side effects:
Example
var x = 123;
var y = new Number(123);
(x === y) // is false because x is a number and y is an object.
Number Properties
Property Description
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
NaN Represents a "Not-a-Number" value
POSITIVE_INFINITY Represents infinity (returned on overflow)
Example
var x = Number.MAX_VALUE;
Number properties belongs to the JavaScript's number object wrapper called Number.
These properties can only be accessed as Number.MAX_VALUE.
Using myNumber.MAX_VALUE, where myNumber is a variable, expression, or value, will
return undefined:
Example
var x = 6;
var y = x.MAX_VALUE; // y becomes undefined
Number methods are covered in the next chapter
Global Methods
Draft Copy 27 | P a g e
JavaScript global functions can be used on all JavaScript data types.
These are the most relevant methods, when working with numbers:
Method Description
Number() Returns a number, converted from its argument.
parseFloat() Parses its argument and returns a floating point number
parseInt() Parses its argument and returns an integer
Number Methods
JavaScript number methods are methods that can be used on numbers:
Method Description
toString() Returns a number as a string
toExponential() Returns a string, with a number rounded and written using exponential notation.
toFixed() Returns a string, with a number rounded and written with a specified number of
decimals.
toPrecision() Returns a string, with a number written with a specified length
valueOf() Returns a number as a number
All number methods return a new variable. They do not change the original variable.
Draft Copy 29 | P a g e
In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof =
object).
The valueOf() method is used internally in JavaScript to convert Number objects to primitive
values.
There is no reason to use it in your code.
In JavaScript, all data types have a valueOf() and a toString() method.
Draft Copy 30 | P a g e
Example
To add two or more string variables together, use the + operator.
txt1 = "What a very";
txt2 = "nice day";
txt3 = txt1 + txt2;
The result of txt3 will be:
What a verynice day
To add a space between the two strings, insert a space into one of the strings:
Example
txt1 = "What a very ";
txt2 = "nice day";
txt3 = txt1 + txt2;
The result of txt3 will be:
What a very nice day
or insert a space into the expression:
Example
txt1 = "What a very";
txt2 = "nice day";
txt3 = txt1 + " " + txt2;
The result of txt3 will be:
What a very nice day
The += operator can also be used to concatenate strings:
Example
txt1 = "What a very ";
txt1 += "nice day";
The result of txt1 will be:
What a very nice day
Draft Copy 32 | P a g e
Math.min() and Math.max()
Math.min() and Math.max() can be used to find the lowest or highest value in a list of
arguments:
Example
Math.min(0, 150, 30, 20, -8); // returns -8
Example
Math.max(0, 150, 30, 20, -8); // returns 150
Math.random()
Math.random() returns a random number between 0 and 1:
Example
Math.random(); // returns a random number
Math.round()
Math.round() rounds a number to the nearest integer:
Example
Math.round(4.7); // returns 5
Math.round(4.4); // returns 4
Math.ceil()
Math.ceil() rounds a number up to the nearest integer:
Example
Math.ceil(4.4); // returns 5
Math.floor()
Math.floor() rounds a number down to the nearest integer:
Example
Math.floor(4.7); // returns 4
Math.floor() and Math.random() can be used together to return a random number between 0 and
10:
Example
Math.floor(Math.random() * 11); // returns a random number between 0 and 10
Math Constants
JavaScript provides 8 mathematical constants that can be accessed with the Math object:
Example
Math.E; // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Draft Copy 33 | P a g e
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
Displaying Dates
In this tutorial we use a script to display dates inside a <p> element with id="demo":
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
The script above says: assign the value of Date() to the content (innerHTML) of the element
with id="demo".
You will learn how to display a date, in a more readable format, at the bottom of this page.
Draft Copy 34 | P a g e
<script>
var d = new Date(0);
document.getElementById("demo").innerHTML = d;
</script>
JavaScript dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC).
One day contains 86,400,000 millisecond.
Using new Date(), with 7 numbers, creates a new date object with the specified date and time:
The 7 numbers specify the year, month, day, hour, minute, second, and millisecond, in that
order:
Example
<script>
var d = new Date(99,5,24,11,33,30,0);
document.getElementById("demo").innerHTML = d;
</script>
Variants of the example above let us omit any of the last 4 parameters:
Example
<script>
var d = new Date(99,5,24);
document.getElementById("demo").innerHTML = d;
</script>
JavaScript counts months from 0 to 11. January is 0. December is 11.
Date Methods
When a Date object is created, a number of methods allow you to operate on it.
Date methods allow you to get and set the year, month, day, hour, minute, second, and
millisecond of objects, using either local time or UTC (universal, or GMT) time.
The next chapter, of this tutorial, covers the date object's methods.
Displaying Dates
When you display a date object in HTML, it is automatically converted to a string, with the
toString() method.
Example
<p id="demo"></p>
<script>
d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
Is the same as:
<p id="demo"></p>
<script>
d = new Date();
document.getElementById("demo").innerHTML = d.toString();
</script>
The toUTCString() method converts a date to a UTC string (a date display standard).
Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toUTCString();
</script>
The toDateString() method converts a date to a more readable format:
Example
Draft Copy 35 | P a g e
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toDateString();
</script>
Date objects are static, not dynamic. The computer time is ticking, but date objects, once created, are not.
Draft Copy 36 | P a g e
Date Set Methods
Set methods are used for setting a part of a date. Here are the most common (alphabitically):
Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day yyyy.mm.dd)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1, 1970)
Draft Copy 37 | P a g e
document.getElementById("demo").innerHTML = d;
</script>
Compare Dates
Dates can easily be compared.
The following example compares today's date with January 14, 2100:
Example
var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);
if (someday > today) {
text = "Today is before January 14, 2100.";
} else {
text = "Today is after January 14, 2100.";
}
document.getElementById("demo").innerHTML = text;
Displaying Arrays
In this tutorial we will use a script to display arrays inside a <p> element with id="demo":
Example
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
The first line (in the script) creates an array named cars.
The second line "finds" the element with id="demo", and "displays" the array in the
"innerHTML" of it.
Example
var cars = [
"Saab",
"Volvo",
"BMW"
];
Don't put a comma after the last element (like "BMW",). It is inconsistent across browsers.
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW";
Draft Copy 38 | P a g e
However, what if you want to loop through the cars and find a specific one? And what if you
had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring
to an index number.
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array-name = [item1, item2, ...];
Example:
var cars = ["Saab", "Volvo", "BMW"];
Draft Copy 40 | P a g e
Use [] instead.
These two different statements both create a new empty array named points:
var points = new Array(); // Bad
var points = []; // Good
These two different statements both create a new array containing 6 numbers:
var points = new Array(40, 100, 1, 5, 25, 10) // Bad
var points = [40, 100, 1, 5, 25, 10]; // Good
The new keyword complicates your code and produces nasty side effects:
var points = new Array(40, 100); // Creates an array with two elements (40 and 100)
What if I remove one of the elements?
var points = new Array(40); // Creates an array with 40 undefined elements !!!!!
Boolean Values
Very often, in programming, you will need a data type that can only have one of two values, like
YES / NO
ON / OFF
TRUE / FALSE
For this, JavaScript has a Boolean data type. It can only take the values true or false.
Draft Copy 41 | P a g e
< less than if (age < 18)
The Boolean value of an expression is the fundament for JavaScript comparisons and conditions.
JavaScript Statements
In HTML, JavaScript statements are "commands" to the browser.
The purpose, of the statements, is to tell the browser what to do.
This statement tells the browser to write "Hello Dolly" inside an HTML element identified with
id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
Draft Copy 42 | P a g e
JavaScript Code
JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
Each statement is executed by the browser in the sequence they are written.
This example will manipulate two different HTML elements:
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
document.getElementById("myDiv").innerHTML = "How are you?";
Semicolon;
Semicolon separates JavaScript statements.
Normally you add a semicolon at the end of each executable statement:
a = 5;
b = 6;
c = a + b;
Multiple statements on one line is allowed:
a = 5; b = 6; c = a + b;
You might see examples without semicolons.
Ending statements with semicolon is optional in JavaScript.
Example:
var patt = /w3schools/i
Example explained:
/w3schools/i is a regular expression.
w3schools is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).
Draft Copy 44 | P a g e
Using String Methods
In JavaScript, regular expressions are often used with the two string methods: search() and
replace().
The search() method uses an expression to search for a match, and returns the position of the
match.
The replace() method returns a modified string where the pattern is replaced.
Draft Copy 45 | P a g e
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |
Metacharacters are characters with a special meaning:
Metacharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning or at the end of a word
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Quantifiers define quantities:
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
Using test()
The test() method is a RegExp expression method.
It searches a string for a pattern, and returns true or false, depending on the result.
The following example searches a string for the character "e":
Example
var patt = /e/;
patt.test("The best things in life are free!");
Since there is an "e" in the string, the output of the code above will be:
true
You don't have to put the regular expression in a variable first. The two lines above can be shortened to
one:
/e/.test("The best things in life are free!")
Using exec ()
The exec() method is a RegExp expression method.
It searches a string for a specified pattern, and returns the found text.
If no match is found, it returns null.
The following example searches a string for the character "e":
Example 1
/e/.exec("The best things in life are free!");
Since there is an "e" in the string, the output of the code above will be:
e
Draft Copy 46 | P a g e
function
There are 3 types of objects:
Object
Date
Array
And 2 data types that cannot contain values:
null
undefined
Draft Copy 47 | P a g e
JavaScript Type Conversion
JavaScript variables can be converted to a new variable and another data type:
By the use of a JavaScript function
Automatically by JavaScript itself
Draft Copy 48 | P a g e
d = new Date();
d.getTime() // returns 1404568027739
Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between
variables or values.
Given that x=5, the table below explains the comparison operators:
Operator Description Comparing Returns Try it
== equal to x == 8 false Try it »
x == 5 true Try it »
=== equal value and equal type x === "5" false Try it »
x === 5 true Try it »
!= not equal x != 8 true Try it »
!== not equal value or not equal type x !== "5" true Try it »
x !== 5 false Try it »
> greater than x>8 false Try it »
< less than x<8 true Try it »
>= greater than or equal to x >= 8 false Try it »
<= less than or equal to x <= 8 true Try it »
Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
Operator Description Example
Draft Copy 49 | P a g e
&& and (x < 10 && y > 1) is true
|| or (x == 5 || y == 5) is false
! not !(x == y) is true
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some
condition.
Syntax
variablename = (condition) ? value1:value2
Example
voteable = (age < 18) ? "Too young":"Old enough";
If the variable age is a value below 18, the value of the variable voteable will be "Too young",
otherwise the value of voteable will be "Old enough".
Conditional Statements
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax
if (condition) {
block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
Example
Make a "Good day" greeting if the time is less than 20:00:
if (time < 20) {
greeting = "Good day";
}
The result of greeting will be:
Draft Copy 50 | P a g e
if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
The result of greeting will be:
Good evening
Draft Copy 52 | P a g e
Common Code and Fall-Through
Sometimes, in a switch block, you will want different cases to use the same code, or fall-
through to a common default.
Note from the next example, that cases can share the same code block, and that the default case
does not have to be the last case in a switch block:
Example
switch (new Date().getDay()) {
case 1:
case 2:
case 3:
default:
text = "Looking forward to the Weekend";
break;
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
}
26. JavaScript For Loop
Loops can execute a block of code a number of times.
JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each time with a
different value. Often this is the case when working with arrays:
Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
You can write:
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
Statement 1
Normally you will use statement 1 to initiate the variable used in the loop (var i = 0).
This is not always the case, JavaScript doesn't care. Statement 1 is optional.
You can initiate many values in statement 1 (separated by comma):
Example:
for (i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
}
And you can omit statement 1 (like when your values are set before the loop starts):
Example:
var i = 2;
var len = cars.length;
var text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}
Statement 2
Often statement 2 is used to evaluate the condition of the initial variable.
This is not always the case, JavaScript doesn't care. Statement 2 is also optional.
If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end.
This will crash your browser. Read about breaks in a later chapter of this tutorial.
Statement 3
Often statement 3 increases the initial variable.
This is not always the case, JavaScript doesn't care, and statement 3 is optional.
Statement 3 can do anything like negative increment (i--), or larger increment (i = i + 15), or
anything else.
Statement 3 can also be omitted (like when you increment your values inside the loop):
Example:
var i = 0;
var len = cars.length;
for (; i < len; ) {
text += cars[i] + "<br>";
i++;
}
for (;cars[i];) {
text += cars[i] + "<br>";
i++;
}
The loop in this example uses a while loop to collect the car names from the cars array:
Example
cars = ["BMW","Volvo","Saab","Ford"];
var i = 0;
var text = "";
while (cars[i]) {
text += cars[i] + "<br>";
i++;
}
JavaScript Break and Continue
JavaScript Labels
Draft Copy 56 | P a g e
As you have already seen, in the chapter about the switch statement, JavaScript statements can
be labeled.
To label JavaScript statements you precede the statements with a label name and a colon:
label:
statements
The break and the continue statements are the only JavaScript statements that can "jump out of"
a code block.
Syntax:
break labelname;
continue labelname;
The continue statement (with or without a label reference) can only be used inside a loop.
The break statement, without a label reference, can only be used inside a loop or a switch.
With a label reference, it can be used to "jump out of" any JavaScript code block:
Example
cars = ["BMW", "Volvo", "Saab", "Ford"];
list: {
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
break list;
text += cars[4] + "<br>";
text += cars[5] + "<br>";
}
28. JavaScript Errors - Throw and Try to Catch
The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
The finally statement lets you execute code, after try and catch, regardless of the result.
Draft Copy 58 | P a g e
}
</script>
</body>
</html>
JavaScript Debugging
It is difficult to write JavaScript code without a debugger.
Your code might contain syntax errors, or logical errors, that are difficult to diagnose.
Often, when JavaScript code contains errors, nothing will happen. There are no error messages,
and you will get no indications where to search for errors.
Normally, errors will happen, every time you try to write some new JavaScript code.
JavaScript Debuggers
Searching for errors in programming code is called code debugging.
Debugging is not easy. But fortunately, all modern browsers have a built-in debugger.
Built-in debuggers can be turned on and of, forcing errors to be reported to the user.
Draft Copy 59 | P a g e
With a debugger, you can also set breakpoints (places where code execution can be stopped),
and examine variables while the code is executing.
Normally, otherwise follow the steps at the bottom of this page, you activate debugging in your
browser with the F12 key, and select "Console" in the debugger menu.
Setting Breakpoints
In the debugger window, you can set breakpoints in the JavaScript code.
At each breakpoint, JavaScript will stop executing, and let you examine JavaScript values.
After examining values, you can resume the execution of code (typically with a play button).
Draft Copy 62 | P a g e
The "use strict"; Syntax
The syntax, for declaring strict mode, was designed to be compatible with older versions of
JavaScript.
Compiling a numeric literal (4 + 5;) or a string literal ("John Doe";) in a JavaScript program has
no side effects. It simply compiles to a non existing variable and dies.
So "use strict;" only matters to new compilers that "understand" the meaning of it.
Other Differences
In function calls like f(), the this value was the global object. In strict mode, it is now undefined.
For security reasons, in strict mode code, eval does not create a new variable in the scope from
which it was called.
With strict mode, you cannot, for example, use undeclared variables.
Watch Out!
The "use strict" directive is only recognized at the beginning of a script or a function.
If you add two JavaScript files into one file, you will lose the effect of the directive in the second
file.
32. JavaScript Coding Conventions
Always use the same coding conventions for all your JavaScript projects.
Coding Conventions
Coding conventions are style guidelines for programming. They typically cover:
Naming and declaration rules for variables and functions.
Rules for the use of white space, indentation, and comments.
Programming practices and principles
Coding conventions secure software quality:
Improves code readability
Make code maintenance easier
Coding conventions can be documented rules for teams to follow, or just be your individual coding
practice.
This page describes the general JavaScript code conventions used by W3Schools.
You should also read the next chapter "Best Practices", and learn how to avoid coding
pitfalls.
Variable Names
At W3schools we use camelCase for identifier names (variable and function). All names start
with a letter.
At the bottom of this page, you will find a wider discussion about naming rules.
firstName = "John";
lastName = "Doe";
price = 19.90;
discount = 0.10;
fullPrice = price * 100 / discount;
Declarations on Top
It is good coding practice to put all declarations at the top of each script or function.
This gives better, cleaner code, and reduces the possibility of accidental re-declarations.
var firstName, lastName;
var price, discount, fullPrice;
firstName = "John";
lastName = "Doe";
price = 19.90;
Draft Copy 64 | P a g e
discount = 0.10;
fullPrice = price * 100 / discount;
This also goes for variables in loops:
var i;
for (i = 0; i < 5; i++)
Since JavaScript moves the declarations to the top anyway (JavaScript hoisting), it is always a
good rule.
Code Indentation
Always use 4 spaces for indentation of code blocks:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
for (i = 1; i < 50; i++) {
sum += i;
}
Do not use tabs (tabulators) for indentation. Text editors interpret tabs differently.
Performance
Coding conventions are not used by computers. Most rules have little impact on the execution
of programs.
Indentation and extra spaces are not significant in small scripts.
For code in development, readability should be preferred. Larger production scripts should be
minifyed.
Naming Conventions
Always use the same naming convention for all your code. For example:
Variable and function names written as camelCase
Global variable written in UPPERCASE
Constants (like PI) written in UPPERCASE
Should you use hyp-hens, camelCase, or under_scores in variable names?
This is a question programmers often discuss. The answer depends on who you ask:
Hyphens in HTML and CSS:
HTML5 attributes can start with data- (data-quantity, data-price).
CSS uses hyphens in property-names (font-size).
Draft Copy 65 | P a g e
Hyphens can be mistaken as subtraction attempts. Hyphens are not allowed in JavaScript names.
Underscores:
Many programmers prefer to use underscores (date_of_birth), especially in SQL databases.
Underscores are often used in PHP documentation.
CamelCase:
CamelCase is often preferred by C programmers.
camelCase:
camelCase is used by JavaScript itself, by jQuery, and other JavaScript libraries.
Don't start names with a $ sign. It will put you in conflict with many JavaScript library names.
Draft Copy 66 | P a g e
var x6 = /()/; // new regexp object
var x7 = function(){}; // new function object
Draft Copy 67 | P a g e
function myFunction(x, y) {
y = y || 0;
}
Draft Copy 68 | P a g e
<script>
window.onload = downScripts;
function downScripts() {
var element = document.createElement("script");
element.src = "myScript.js";
document.body.appendChild(element);
}
</script>
JavaScript Standards
All modern browsers fully support ECMAScript 3 (ES3, the third edition of JavaScript from
1999).
ECMAScript 4 (ES4) was never adopted.
ECMAScript 5 (ES5, released in 2009) is the latest official version of JavaScript.
Time passes, and we are now beginning to see complete support for ES5 in all modern
browsers.
Nonstandard JavaScript
In addition to reserved words, there are also some nonstandard keywords used in some
JavaScript implementations.
One example is the const keyword used to define variables. Some JavaScript engines will treat
const as a synonym to var. Other engines will treat const as a definition for read-only variables.
Const is an extension to JavaScript. It is supported by the JavaScript engine used in Firefox and
Chrome. But it is not a part of the JavaScript standards ES3 or ES5. Do not use it.
What is JSON?
JSON stands for JavaScript Object Notation
JSON is lightweight data interchange format
JSON is language independent *
JSON is "self-describing" and easy to understand
* JSON uses JavaScript syntax, but the JSON format is text only.
Text can be read and used as a data format by any programming language.
JSON Example
Draft Copy 70 | P a g e
This JSON syntax defines an employees object: an array of 3 employee records (objects):
JSON Example
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
JSON Objects
JSON objects are written inside curly braces.
Just like in JavaScript, objects can contain multiple name/values pairs:
{"firstName":"John", "lastName":"Doe"}
JSON Arrays
JSON arrays are written inside square brackets.
Just like in JavaScript, an array can contain objects:
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
In the example above, the object "employees" is an array. It contains three objects.
Each object is a record of a person (with a first name and a last name).
Draft Copy 71 | P a g e
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
Draft Copy 72 | P a g e