Js Sandeep
Js Sandeep
JavaScript.
My First JavaScript
JavaScript Introduction
JavaScript is the most popular programming language in the
can do.
Did You Know?
JavaScript and Java are completely different languages, both in concept and
design.
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard
in 1997.
ECMA-262 is the official name. ECMAScript 5 (JavaScript 1.8.5 - July 2010) is the
latest standard.
JavaScript can be placed in the <body> and the <head> sections of an HTML
page.
Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
For example, a function can be executed when an event occurs, like when the user
clicks a button.
You will learn much more about functions and events in later chapters.
JavaScript in <head> or <body>
You can place any number of scripts in an HTML document.
Scripts can be placed in the <body>, or in the <head> section of an HTML page,
or in both.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
</body>
</html>
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML
Example
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
loading.
External JavaScript
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 src (source)
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 the <script> tag is
located.
Using window.alert()
You can use an alert box to display data:
Example
<!DOCTYPE html>
<html>
<body>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Using document.write()
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using document.write() after an HTML document is fully loaded, will delete all
existing HTML:
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
The id attribute defines the HTML element. The innerHTML property defines the HTML
content:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Using console.log()
In your browser, you can use the console.log() method to display
data. Activate the browser console with F12, and select "Console" in the
menu.
Example
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
JavaScript Syntax
JavaScript syntax is the rules, how JavaScript programs are constructed.
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by the
called statements.
var x =
5; var y
= 6;
var z = x + y;
In HTML, JavaScript programs can be executed by the web browser.
JavaScript Statements
JavaScript statements are composed of:
JavaScript Values
The JavaScript syntax defines two types of values: Fixed values and variable
values. Fixed values are called literals. Variable values are called variables.
JavaScript Literals
The most important rules for writing fixed values are:
10.50
1001
"John Doe"
'John Doe'
Expressions can also represent fixed values:
5+6
5 * 10
JavaScript Variables
In a programming language, variables are used to store data
var x;
x = 6;
JavaScript Operators
JavaScript uses an assignment operator ( = ) to assign values to variables:
var x =
5; var y
= 6;
(5 + 6) * 10
JavaScript Keywords
JavaScript keywords are used to identify actions to be
new variable:
var x = 5 +
6; var y = x
* 10;
Try it Yourself »
JavaScript Comments
Not all JavaScript statements are "executed".
lastName = "Doe";
lastname = "Peterson";
JavaScript does not interpret VAR or Var as the keyword var.
Unicode covers (almost) all the characters, punctuations, and symbols in the world.
JavaScript Statements
In HTML, JavaScript statements are "instructions" to be "executed" by the web
browser.
JavaScript Statements
This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
JavaScript Programs
Most JavaScript programs contain many JavaScript statements.
The statements are executed, one by one, in the same order as they are
displayed:
Example
var x =
5; var y
= 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
JavaScript programs (and JavaScript statements) are often called JavaScript code.
Semicolons ;
Semicolons separate JavaScript statements.
a = 5;
b = 6;
c = a + b;
a = 5; b = 6; c = a + b;
If a JavaScript statement does not fit on one line, the best place to break it, is
after an operator:
Example
document.getElementById("demo").innerHTML =
"Hello Dolly.";
together.
One place you will find statements grouped together in blocks, are in JavaScript
functions:
Example
function myFunction() {
document.getElementById("demo").innerHTML = "Hello Dolly.";
document.getElementById("myDIV").innerHTML = "How are you?";
}
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action
to be performed.
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging
function
do ... while Executes a block of statements, and repeats the block, while a condition is
true
for Marks a block of statements to be executed, as long as a condition is
true
function Declares a function
if ... else Marks a block of statements to be executed, depending on a condition
return Exits a function
switch Marks a block of statements to be executed, depending on different
cases
try ... catch Implements error handling to a block of statements
var Declares a variable
JavaScript keywords are reserved words. Reserved words cannot be used as names
for variables.
JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it more
readable.
Any text between // and the end of a line, will be ignored by JavaScript (will
not be executed).
This example uses a single line comment before each line, to explain the code:
Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
This example uses a single line comment at the end of each line, to explain the code:
Example
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 */.
This 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.";
Adding // in front of a code line changes the code lines from an executable line
to a comment.
Example
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
Example
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/
JavaScript Variables
JavaScript variables are containers for storing data
Example
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
From the example above, you can calculate the total to be 11.00
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y), or more descriptive names
(age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
operator. This is different from algebra. The following does not make sense in
algebra:
x=x+5
(It calculates the value of x + 5 and puts the result into x. The value of x is
incremented by 5)
Strings are written inside double or single quotes. Numbers are written without quotes.
Example
var pi = 3.14;
var person = "John
Doe"; var answer = 'Yes
I am!';
var carName;
equal sign:
carName = "Volvo";
In the example below, we create a variable called carName and assign the value "Volvo"
to it.
Example
<p id="demo"></p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
price = 200;
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.
The variable carName will have the value undefined after the execution of this
statement:
Example
var carName;
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable, it will not lose its value.
The variable carName will still have the value "Volvo" after the execution of these
statements:
Example
var carName =
"Volvo"; var
carName;
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like
= and +:
Example
var x = 5 + 2 + 3;
You can also add strings, but strings will be concatenated (added end-to-end):
Example
var x = "John" + " " +
Example
var x = "5" + 2 + 3;
If you add a number to a string, the number will be treated as string,
and concatenated.
JavaScript Operators
Example
Assign values to variables and add them together:
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
Adding
var x =
5; var y
= 2;
var z = x + y;
Multiplying
var x = 5;
var y = 2;
var z = x *
y;
Dividing
var x = 5;
var y = 2;
var z = x /
y;
Modulus
var x =
5; var y
= 2;
var z = x % y;
Incrementing
var x =
5; x++;
var z = x;
The decrement operator (--) decrements a value.
Decrementing
var x =
5; x--;
var z = x;
Assignment
var x = 10;
Assignment
var x =
10; x +=
5;
Assignment
var x =
10; x *=
5;
Assignment
var x =
10; x /=
5;
Assignment
var x =
10; x %=
5;
Example
To add two or more string variables together, use the + operator.
txt1 = "What a
very"; txt2 = "nice
day"; txt3 = txt1
+ txt2;
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;
Example
txt1 = "What a
very"; txt2 = "nice
day";
txt3 = txt1 + " " + txt2;
Example
txt1 = "What a very
"; txt1 += "nice
day";
Example
x = 5 + 5;
y = "5" + 5;
z= "Hello" + 5;
10
55
Hello5
The rule is: If you add a number and a string, the result will be a string!
var x = 16 + "Volvo"
Does it make any sense to add "Volvo" to sixteen? Will produce an error or a
Example
var x = "16" + "Volvo"
Example
var x; // Now x is
undefined var x = 5; //
Now x is a Number var x =
"John"; // Now x is a
String
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
JavaScript Numbers
JavaScript has only one type of numbers.
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 = // 12300000
123e5;
var z = 123e- // 0.00123
5;
JavaScript Booleans
Booleans can only have two values: true or false.
Example
var x =
true; var y
= false;
You will learn more about conditional testing later in this tutorial.
JavaScript Arrays
JavaScript arrays are written with square
commas.
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.
JavaScript Objects
JavaScript objects are written with curly braces.
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.
Example
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof false // Returns boolean
typeof [1,2,3,4] // Returns object
typeof {name:'John', age:34} // Returns object
In JavaScript, an array is a special type of object. Therefore typeof [1,2,3,4] returns
object.
Undefined
In JavaScript, a variable without a value, has the value undefined. The typeof is
also
undefined.
Example
var person; // The value is undefined, the typeof is undefined
Try it Yourself »
Empty Values
An empty value has nothing to do with
Example
var car = ""; // The value is "", the typeof is string
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular
(calls it).
Example
function myFunction(p1, p2) {
return p1 * p2; // the function returns the product of p1 and p2
}
Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
Function arguments are the real values received by the function when it is invoked.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:
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:
in x function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
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);
}
document.getElementById("demo").innerHTML = toCelsius(32);
Example
Accessing a function without () will return the function definition:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;
Example
Instead of:
temp = toCelsius(32);
text = "The temperature is " + temp + "
You will learn a lot more about functions later in this tutorial.
JavaScript Objects
Real Life Objects, Properties, and Methods
In real life, a car is an object.
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
You have already learned that JavaScript variables are containers for data
values. This code assigns a simple value (Fiat) to a variable named car:
var car = "Fiat";
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
The values are written as name:value pairs (name and value separated by a
Object Properties
The name:values pairs (in JavaScript objects) are called properties.
Object Methods
Methods are actions that can be performed on
function definitions.
Object Definition
You define (and create) a JavaScript object with an object literal:
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"
};
objectName.propertyName
or
objectName[propertyName]
Example1
person.lastName;
Example2
person["lastName"];
objectName.methodName()
Example
name = person.fullName();
If you access the fullName property, without (), it will return the function definition:
Example
name = person.fullName;
JavaScript Scope
Scope is the set of variables you have access to.
In JavaScript, scope is the set of variables, objects, and functions you have
access to.
Local variables have local scope: They can only be accessed within the
function.
Example
// code here can not use
carName function
myFunction() {
var carName = "Volvo";
}
Since local variables are only recognized inside their functions, variables with the same
name can be used in different functions.
Local variables are created when a function starts, and deleted when the function is
completed.
A global variable has global scope: All scripts and functions on a web page can
access it.
Example
var carName = " Volvo";
carName function
myFunction() {
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";
Function Arguments
Function arguments (parameters) work as local variables inside functions.
In HTML, the global scope is the window object: All global variables belong
to the window object.
Example
// code here can use
window.carName function
myFunction() {
carName = "Volvo";
}
JavaScript Events
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can "react" on these events.
HTML Events
An HTML event can be something the browser does, or something a user
are detected.
HTML allows event handler attributes, with JavaScript code, to be added to HTML
elements.
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>
Example
<button onclick="displayDate()">The time is?</button>
Common HTML Events
Here is a list of some common HTML events:
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
Many different methods can be used to let JavaScript work with events:
You will learn a lot more about events and event handlers in the HTML
DOM chapters.
JavaScript Strings
JavaScript strings are used for storing and manipulating text.
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"';
String Length
The length of a string is found in the built in property length:
Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Special Characters
Because strings must be written within quotes, JavaScript will misunderstand this string:
The backslash escape character turns special characters into string characters:
Example
var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north."
The escape character (\) can also be used to insert other special characters in a
string.
This is the lists of 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
document.getElementById("demo").innerHTML =
"Hello Dolly.";
You can also break up a code line within a text string with a single backslash:
Example
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
Example
document.getElementById("demo").innerHTML = \
"Hello Dolly!";
But strings can also be defined as objects with the keyword new: var firstName
= new String("John")
Example
var x = "John";
var y = new String("John");
// type of x will return String
// type of y will return Object
Don't create strings as objects. It slows down execution speed, and produces nasty side
effects:
Example
var x = "John";
var y = new String("John");
When using the === equality operator, equal strings are not equal:
Example
var x = "John";
var y = new String("John");
and value.
But with JavaScript, methods and properties are also available to primitive
values, because JavaScript treats primitive values as objects when executing
methods and properties.
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)
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
JavaScript String Methods
String methods help you to work with strings.
Example
var str = "Please locate where 'locate'
occurs!"; var pos = str.indexOf("locate");
The lastIndexOf() method returns the index of the last occurrence of a specified text
in a string:
Example
var str = "Please locate where 'locate'
occurs!"; var pos =
str.lastIndexOf("locate");
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not
found.
Both methods accept a second parameter as the starting position for the
search.
They accept the same arguments (parameters), and they return the same value.
The two methods are equal, but the search() method can take much more
powerful search values.
You will learn more about powerful search values in the chapter about
regular expressions.
slice(start, end)
substring(start, end)
substr(start, length)
The method takes 2 parameters: the starting index (position), and the ending
index (position).
This example slices out a portion of a string from position 7 to position 13:
Example
var str = "Apple, Banana, Kiwi";
var res = str.slice(7,13);
Banana
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:
Example
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12,-6);
Banana
If you omit the second parameter, the method will slice out the rest of the
string:
Example
var res = str.slice(7);
Example
var res = str.slice(-12);
Negative positions does not work in Internet Explorer 8 and earlier.
Example
var str = "Apple, Banana, Kiwi";
var res = str.substring(7,13);
Banana
If you omit the second parameter, substring() will slice out the rest of the
string.
The difference is that the second parameter specifies the length of the extracted
part.
Example
var str = "Apple, Banana,
Kiwi"; var res =
str.substr(7,6);
Banana
If the first parameter is negative, the position counts from the end of the
Example
str = "Please visit Microsoft!";
var n = str.replace("Microsoft","W3Schools");
The replace() method can also take a regular expression as the search value.
Example
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1 converted to upper
Example
var text1 = "Hello World!"; // String
var text2 = text1.toLowerCase(); // text2 is text1 converted to lower
Example
var text1 =
"Hello"; var text2
= "World";
text3 = text1.concat(" ",text2);
The concat() method can be used instead of the plus operator. These two lines do the
same:
Example
var text = "Hello" + " " +
"World!"; var text = "Hello".concat("
","World!");
All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.
charAt(position)
charCodeAt(position)
Example
var str = "HELLO WORLD";
str.charAt(0); // returns
H
The charCodeAt() Method
The charCodeAt() method returns the unicode of the character at a specified index in
a string:
Example
var str = "HELLO WORLD";
str.charCodeAt(0); // returns
72
str[0]; // returns H
If the separator is omitted, the returned array will contain the whole string in
index [0]. If the separator is "", the returned array will be an array of single
characters:
Example
var txt = "Hello"; // String
txt.split(""); // Split in
characters
JavaScript Numbers
JavaScript has only one type of number.
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
JavaScript numbers are always stored as double precision floating point numbers,
following the international IEEE 754 standard.
This format stores numbers in 64 bits, where the number (the fraction) is stored in
bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:
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
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
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
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;
}
Example
var x = 2 / 0; // x will be
Infinity var y = -2 / 0; // y
will be -Infinity
Example
typeof Infinity; // returns "number"
Example
var x = 100 / "Apple"; // x will be NaN (Not a Number)
However, if the string contains a numeric value , the result will be a number:
Example
var x = 100 / "10"; // x will be 10
You can use the global JavaScript function isNaN() to find out if a value is a
number.
Example
var x = 100 / "Apple";
isNaN(x); // returns true because x is Not a Number
Watch out for NaN. If you use NaN in a mathematical operation, the result will also
be NaN.
Example
var x =
NaN; var y
= 5;
var z = x + y; // z will be NaN
But numbers can also be defined as objects with the keyword new: var y = new
Number(123)
Example
var x = 123;
var y = new Number(123);
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.
But with JavaScript, methods and properties are also available to primitive
values, because JavaScript treats primitive values as objects when executing
methods and properties.
Number Properties
Property Description
Example
var x = Number.MAX_VALUE;
Example
var x = 6;
var y = x.MAX_VALUE; // y becomes undefined
Global Methods
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
Returns a string, with a number rounded and written
toExponential()
using exponential notation.
Returns a string, with a number rounded and written
toFixed()
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.
Example
var x = 123;
x.toString(); // returns 123 from variable
x (123).toString(); // returns 123 from literal
123
(100 + 23).toString(); // returns 123 from expression 100 + 23
Example
var x = 9.656;
x.toExponential(2); // returns 9.66e+0
x.toExponential(4); // returns 9.6560e+0
x.toExponential(6); // returns
9.656000e+0
The parameter is optional. If you don't specify it, JavaScript will not round the
number.
The toFixed() Method
toFixed() returns a string, with the number written with a specified number of
decimals:
Example
var x = 9.656;
x.toFixed(0); // returns 10
x.toFixed(2); // returns 9.66
x.toFixed(4); // returns
9.6560 x.toFixed(6); // returns
9.656000
Example
var x = 9.656;
x. toPrecision();
// returns 9.656 x.toPrecision(2);
// returns 9.7
x.toPrecision(4); // returns 9.656
x.toPrecision(6); // returns
9.65600
These methods are not number methods, but global JavaScript methods.
Example
x = true;
Number(x); // returns
1 x = false;
Number(x); // returns
0 x = new Date();
Number(x); // returns
1404568027739 x = "10"
Number(x); // returns
10 x = "10 20"
Number(x); // returns NaN
Example
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns
10 parseInt("10 years"); //
returns 10 parseInt("years 10"); //
returns NaN
If the number cannot be converted, NaN (Not a Number) is returned.
Example
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns
10.33 parseFloat("10 20 30"); //
returns 10 parseFloat("10 years"); //
returns 10 parseFloat("years 10"); //
returns NaN
Example
var x = 123;
x.valueOf(); // returns 123 from variable
x (123).valueOf(); // returns 123 from literal
123
(100 + 23).valueOf(); // returns 123 from expression 100 + 23
Example
Math.random(); // returns a random number
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
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
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.
constructor.
Using new Date(), creates a new date object with the current date and time:
Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
Using new Date(date string), creates a new date object from the specified date
and time:
Example
<script>
var d = new Date("October 13, 2014 11:13:00");
document.getElementById("demo").innerHTML = d;
</script>
Using new Date(number), creates a new date object as zero time plus the
number. Zero time is 01 January 1970 00:00:00 UTC. The number is specified in
milliseconds:
Example
<script>
var d = new Date(86400000);
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(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>
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>
<p id="demo"></p>
<script>
d = new Date();
document.getElementById("demo").innerHTML = d.toString();
</script>
Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toUTCString();
</script>
Example
<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.
Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday as a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1, 1970)
Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getTime();
</script>
Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();
</script>
The getDay() Method
getDay() returns the weekday as a number (0-6):
Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getDay();
</script>
You can use an array of names, and getDay() to return the weekday as a name:
Example
<script>
var d = new Date();
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.getElementById("demo").innerHTML = days[d.getDay()];
</script>
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)
The setFullYear() Method
setFullYear() sets a date object to a specific date. In this example, to January 14,
2020:
Example
<script>
var d = new Date();
d.setFullYear(2020, 0, 14);
document.getElementById("demo").innerHTML = d;
</script>
Example
<script>
var d = new
Date();
d.setDate(20);
document.getElementById("demo").innerHTML = d;
</script>
Example
<script>
var d = new Date();
d.setDate(d.getDate() + 50);
document.getElementById("demo").innerHTML = d;
</script>
If adding days, shifts the month or year, the changes are handled automatically
by the Date object.
Date.parse() returns the number of milliseconds between the date and January 1,
1970:
Example
<script>
var msec = Date.parse("March 21, 2012");
document.getElementById("demo").innerHTML = msec;
</script>
You can then use the number of milliseconds to convert it to a date object:
Example
<script>
var msec = Date.parse("March 21, 2012");
var d = new Date(msec);
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);
JavaScript Arrays
JavaScript arrays are used to store multiple values in a single variable.
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.
Try it Yourself
Create an array, and assign values to it:
Example
var cars = ["Saab", "Volvo", "BMW"];
Spaces and line breaks are not important. A declaration can span multiple lines:
Example
var cars =
[ "Saab"
,
"Volvo",
"BMW"
];
Never put a comma after the last element (like "BMW",). The effect 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";
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?
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:
...]; Example:
The two examples above do exactly the same. There is no need to use new
Array().
For simplicity, readability and execution speed, use the first one (the array literal
method).
cars[0] = "Opel";
[0] is the first element in an array. [1] is the second. Array indexes start
with 0.
You can have objects in an Array. You can have functions in an Array. You
can have arrays in an Array:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns
"object" for arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns
John:
Array:
var person = ["John", "Doe",
Object:
var person = {firstName:"John", lastName:"Doe", age:46};
Examples
var x = cars.length; // The length property returns the number of elements in
cars var y = cars.sort(); // The sort() method sort cars in alphabetical order
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits
is 4
The length property is always one more than the highest array index.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
Adding elements with high indexes can create undefined "holes" in an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[10] = "Lemon"; // adds a new element (Lemon) to fruits
Associative Arrays?
Many programming languages support arrays with named indexes.
indexes.
Example:
var person = []
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length; // person.length will return
3 var y = person[0]; // person[0] will return
"John"
If you use a named index, when accessing an array, JavaScript will redefine the array to a
standard object, and all array methods and properties will produce undefined or
incorrect results.
Example:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length will return 0
var y = person[0]; // person[0] will return
undefined
indexes.
Use [] instead.
These two different statements both create a new empty array named
These two different statements both create a new array containing 6 numbers:
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
"Mango"];
object. To solve this problem you can create your own isArray()
function:
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
The valueOf() method is the default behavior for an array. It returns an array as a
string:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.valueOf();
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
The join() method also joins all array elements into a string.
It behaves just like toString(), but you can specify the separator:
Example
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange","Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
</script>
Popping and Pushing
When you work with arrays, it is easy to remove elements and add new
elements.
This is what popping and pushing is: Popping items out of an array, or pushing
items into an array.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from fruits
The push() method adds a new element to an array (at the end):
Remember: [0] is the first element in an array. [1] is the second. Array indexes start
with 0.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to
fruits
The shift() method removes the first element of an array, and "shifts" all other
elements one place down.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from fruits
The unshift() method adds a new element to an array (at the beginning), and
"unshifts" older elements:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to
fruits
The shift() method returns the string that was "shifted out".
Changing Elements
Array elements are accessed using their index number:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi"; // Changes the first element of fruits to "Kiwi"
The length property provides an easy way to append a new element to an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to
fruit
Deleting Elements
Since JavaScript arrays are objects, elements can be deleted by using the
JavaScript operator delete:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined
Using delete on array elements leaves undefined holes in the array. Use pop() or
splice() instead.
Splicing an Array
The splice() method can be used to add new items to an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
The first parameter (2) defines the position where new elements should be added
(spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be
added.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0,1); // Removes the first element of
fruits
The first parameter (0) defines the position where new elements should be
added
(spliced in).
The second parameter (1) defines how many elements should be removed.
The rest of the parameters are omitted. No new elements will be added.
Sorting an Array
The sort() method sorts an array alphabetically:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of
fruits
Reversing an Array
The reverse() method reverses the elements in an
descending order:
Example
var fruits = ["Banana", "Orange", "Apple",
"Mango"]; fruits.sort(); // Sorts the elements of
fruits fruits.reverse(); // Reverses the order
of the elements
Numeric Sort
By default, the sort() function sorts values as strings.
However, if numbers are sorted as strings, "25" is bigger than "100", because
"2" is bigger than "1".
Because of this, the sort() method will produce incorrect result when sorting numbers.
Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
Use the same trick to sort an array descending:
Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
When the sort() function compares two values, it sends the values to the compare
function, and sorts the values according to the returned (negative, zero, positive) value.
Example:
When comparing 40 and 100, the sort() method calls the compare
negative value).
Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
// now points[0] contains the highest value
Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
// now points[0] contains the lowest value
Joining Arrays
The concat() method creates a new array by concatenating two arrays:
Example
var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias","Linus"];
var myChildren = myGirls.concat(myBoys); // Concatenates (joins) myGirls and myBoys
Example
var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias","Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with arr2 and arr3
Slicing an Array
The slice() method slices out a piece of an array:
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3);
JavaScript Booleans
A JavaScript Boolean represents one of two values: true or false.
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.
Example
Boolean(10 > 9) // returns true
Try it Yourself »
Or even easier:
Example
(10 > 9) // also returns true
10 > 9 // also returns true
True Examples
100
3.14
-15
"Hello"
"false"
7 + 1 + 3.14
5<6
false: var x = 0;
Boolean(x); // returns false
false: var x;
Boolean(x); // returns false
The Boolean value of null is false:
var x = null;
Boolean(x); // returns false
But with JavaScript, methods and properties are also available to primitive
values, because JavaScript treats primitive values as objects when executing
methods and properties.
JavaScript Comparison and Logical
Operators
Comparison and Logical operators are used to test for true or false.
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:
You will learn more about the use of conditional statements in the next chapter
of this tutorial.
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:
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".
The result in x:
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
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
statements:
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:
Good day
The else Statement
Use the else statement to specify a block of code to be executed if the condition is
false.
if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}
Example
If the time is less than 20:00, create a "Good day" greeting, otherwise "Good
evening":
Good day
Syntax
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
Example
If time is less than 10:00, create a "Good morning" greeting, if not, but time is
less than 20:00, create a "Good day" greeting, otherwise a "Good evening":
Good day
Example
Use today's weekday number to calculate weekday name: (Sunday=0, Monday=1,
Tuesday=2, ...)
Monday
This will stop the execution of more execution of code and/or case testing
inside the block.
When a match is found, and the job is done, it's time for a
break. There is no need for more testing.
Example
If today is neither Saturday nor Sunday, write a default message:
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";
}
JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each time
with a different value.
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>";
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been
executed.
Example
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
Statement 2 defines the condition for the loop to run (i must be less than 5).
Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
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.
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 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++;
}
Example
var person = {fname:"John", lname:"Doe", age:25};
Syntax
while (condition) {
code block to be executed
}
Example
In the following example, the code in the loop will run, over and over again, as long
as a variable (i) is less than 10:
Example
while (i < 10) {
text += "The number is "
+ i; i++;
}
If you forget to increase the variable used in the condition, the loop will never
end. This will crash your browser.
Syntax
do {
code block to be executed
}
while (condition);
Example
The example below uses a do/while loop. The loop will always be executed at least
once, even if the condition is false, because the code block is executed before the
condition is tested:
Example
do {
text += "The number is "
+ i; i++;
}
while (i < 10);
Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
Comparing For and While
If you have read the previous chapter, about the for loop, you will discover that a
while loop is much the same as a for loop, with statement 1 and statement 3
omitted.
The loop in this example uses a for loop to collect the car names from the cars
array:
Example
cars = ["BMW","Volvo","Saab","Ford"];
var i = 0;
var text = "";
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++;
}
The break statement breaks the loop and continues executing the code after the
loop (if any):
Example
for (i = 0; i < 10; i+
+) { if (i == 3) {
break }
text += "The number is " + i + "<br>";
}
Since the if statement has only one single line of code, the braces can be
omitted:
JavaScript Labels
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>";
}
Example
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof false // Returns boolean
typeof [1,2,3,4] // Returns object
typeof {name:'John', age:34} // Returns object
You can consider it a bug in JavaScript that typeof null is an object. It should be
null.
Example
var person = null; // Value is null, but type is still an object
Example
var person = undefined; // Value is undefined, type is undefined
Undefined
In JavaScript, undefined is a variable with no
undefined.
Example
var person; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined. The type will also be
undefined.
Example
person = undefined; // Value is undefined, type is undefined
string
number
boolean
object
function
Object
Date
Array
And 2 data types that cannot contain values:
null
undefined
Example
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof NaN // Returns number
typeof false // Returns boolean
typeof [1,2,3,4] // Returns object
typeof {name:'John', age:34} // Returns
object typeof new Date()
// Returns object
typeof function () {} // Returns function
typeof myCar // Returns undefined (if myCar is not
declared) typeof null// Returns object
Please observe:
Example
"John".constructor // Returns function String() { [native code] }
(3.14).constructor // Returns function Number() { [native code]
} false.constructor // Returns function Boolean() { [native code]
} [1,2,3,4].constructor // Returns function Array() { [native code]
}
{name:'John', age:34}.constructor // Returns function Object() { [native
code] } new Date().constructor // Returns
function Date() { [native code] } function () {}.constructor
// Returns function Function(){ [native code]
}
You can check the constructor property to find out if an object is an Array
(contains the word "Array"):
Example
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
You can check the constructor property to find out if an object is a Date
(contains the word "Date"):
Example
function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}
JavaScript Type Conversion
JavaScript variables can be converted to a new variable and another data type:
Example
String(x) // returns a string from a number
variable x String(123) // returns a string from a
number literal 123
String(100 + 23) // returns a string from a number from an expression
Example
x.toString()
(123).toString()
(100 + 23).toString()
Method Description
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
Converting Booleans to Strings
The global method String() can convert booleans to
false.toString() // returns
"false" true.toString() //
returns "true"
Example
Date().toString() // returns Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight
Time)
Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1, 1970)
Method Description
parseFloat() Parses a string and returns a floating point
number
parseInt() Parses a string and returns an integer
Example
var y = "5"; // y is a string
var x = + y; // x is a
number
If the variable cannot be converted, it will still become a number, but with the
value NaN (Not a number):
Example
var y = "John"; // y is a string
var x = + y; // x is a number (NaN)
document.getElementById("demo").innerHTML = myVar;
GMT+0200" Numbers and booleans are also converted, but this is not very
visible:
The search pattern can be used for text search and text replace
operations.
pattern. Regular expressions can be used to perform all types of text search
Syntax
/pattern/modifiers;
Example:
var patt = /w3schools/i
Example explained:
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.
Example
Use a string to do a search for "W3schools" in a string:
Expression Example
Use a case insensitive regular expression to replace Microsoft with W3Schools in a
string:
Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all matches rather than stopping after
the first match)
m Perform multiline matching
Regular Expression Patterns
Brackets are used to find a range of characters:
Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with
|
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
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:
Using exec()
The exec() method is a RegExp expression method.
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
JavaScript Errors - Throw and Try
to Catch
The try statement lets you test a block of code for
error.
The finally statement lets you execute code, after try and catch, regardless of the
result.
Errors can be coding errors made by the programmer, errors due to wrong input,
and other unforeseeable things:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
</html>
In the example above we have made a typo in the code (in the try
block). The catch block catches the error, and executes code to
handle it.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
The technical term for this is: JavaScript will throw an error.
If you use throw together with try and catch, you can control program
flow and generate custom error messages.
The exception (err) is caught by the catch statement and a custom error message is
displayed:
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
x = Number(x);
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a
number"; if(x > 10) throw "is too
high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Input " + err;
}
}
</script>
</body>
</html>
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}
Example
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
x = Number(x);
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a
number"; if(x > 10) throw "is too
high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Error: " + err + ".";
}
finally {
document.getElementById("demo").value = "";
}
}
JavaScript Debugging
You will soon get lost, writing JavaScript code without a debugger.
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
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.
Example
<!DOCTYPE html>
<html>
<body>
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
</body>
</html>
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).
has no effect.
With the debugger turned on, this code will stop executing before it executes the
third line.
Example
var x = 15 *
5; debugger;
document.getElementbyId("demo").innerHTML = x;
Chrome
Open the browser.
From the menu, select tools.
From tools, choose developer tools.
Finally, select Console.
Firefox Firebug
Open the browser.
Go to the web page:
http://www.getfirebug.com.
Follow the instructions how
to: install Firebug
Internet Explorer
Open the browser.
From the menu, select tools.
From tools, choose developer tools.
Finally, select Console.
Opera
Open the browser.
Go to the webpage:
http://dev.opera.com/articles/view/opera-developer-tools.
Follow the instructions how to:
add a Developer Console button to your toolbar.
Safari Firebug
Open the browser.
Go to the webpage:
http://extensions.apple.com.
Follow the instructions how
to: install Firebug Lite.
JavaScript Hoisting
Hoisting is JavaScript's default behavior of moving declarations to the top.
Example 1
x = 5; // Assign 5 to x
var x; // Declare x
Example 2
var x; // Declare x
x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an
element elem.innerHTML = x; // Display x in the
element
Example 1
var x = 5; //
Initialize x var y =
7; // Initialize y
Example 2
var x = 5; // Initialize x
var y = 7; // Initialize y
Because of hoisting, y has been declared before it is used, but because initializations are
not hoisted, the value of y is undefined.
Example
var x = 5; //
Initialize x var y; //
Declare y
y = 7; // Assign 7 to y
(errors).
To avoid bugs, always declare all variables at the beginning of every scope.
rule.
JavaScript in strict mode does not allow variables to be used if they are not
declared. Study "using strict"; in the next chapter.
The purpose of "use strict" is to indicate that the code should be executed in
"strict mode".
With strict mode, you can not, for example, use undeclared variables.
Declared at the beginning of a JavaScript file, it has global scope (all code will
execute in strict mode).
Declared inside a function, it has local scope (only the code inside the function is
in strict mode).
Global declaration:
"use strict";
x = 3.14; // This will cause an error
myFunction(); // This will also cause an
error
function myFunction() {
x = 3.14;
}
Local declaration:
function myFunction() {
"use strict";
x = 3.14;
}
So "use strict;" only matters to new compilers that "understand" the meaning of it.
Strict mode changes previously accepted "bad syntax" into real errors.
In normal JavaScript, a developer will not receive any error feedback assigning values
to non-writable properties.
allowed:
"use strict";
var x = {p1:10, p1:20}; // This will cause an
allowed:
"use strict";
function x(p1, p1) {}; // This will cause an error
allowed:
"use strict";
var obj =
{};
obj.defineProperty(obj, "x", {value:0,
allowed:
"use strict";
var obj = {get x() {return 0} };
allowed:
"use strict";
delete Object.prototype; // This will cause an
variable:
"use strict";
var eval = 3.14; // This will cause an error
"use strict";
var arguments = 3.14; // This will cause an
"use strict";
with (Math){x = cos(2)}; // This will cause an error
For security reasons, eval() are not allowed to create variables in the scope from which it
was called:
"use strict";
eval ("var x = 2");
alert (x) // This will cause an error
In function calls like f(), the this value was the global object. In strict mode, it
is now undefined.
implements
interface
package
private
protected
public
static
yield
Watch Out!
The "use strict" directive is only recognized at the beginning of a script
or a function.
Variable Names
At W3schools we use camelCase for identifier names (variables and
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;
Examples:
var x = y + z;
var values = ["Volvo", "Saab", "Fiat"];
Code Indentation
Always use 4 spaces for indentation of code blocks:
Functions:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-
32);
}
Do not use tabs (tabulators) for indentation. Text editors interpret tabs
differently.
Statement Rules
General rules for simple statements:
Examples:
var values = ["Volvo", "Saab", "Fiat"];
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Functions:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-
32);
}
Loops:
for (i = 0; i < 5; i+
+) { x += i;
}
Conditionals:
if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
Object Rules
General rules for object definitions:
Place the opening bracket on the same line as the object name.
Use colon plus one space between each property and it's value.
Use quotes around string values, not around numeric values.
Do not add a comma after the last property-value pair.
Place the closing bracket, on a new line, without leading spaces.
Always end an object definition with a semicolon.
Example:
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
If a JavaScript statement does not fit on one line, the best place to break it, is
after an operator or a comma.
Example
document.getElementById("demo").innerHTML =
"Hello Dolly.";
Naming Conventions
Always use the same naming convention for all your code. For example:
This is a question programmers often discuss. The answer depends on who you ask:
Underscores:
Many programmers prefer to use underscores (date_of_birth), especially in SQL
databases.
CamelCase:
camelCase:
Don't start names with a $ sign. It will put you in conflict with many
JavaScript library names.
<script src="myscript.js">
File Extensions
HTML files should have a .html extension (not .htm).
CSS files should have a .css
.js extension.
If you use a mix of upper and lower case, you have to be extremely consistent.
If you move from a case insensitive, to a case sensitive server, even small errors will
break your web.
To avoid these problems, always use lower case file names (if possible).
Performance
Coding conventions are not used by computers. Most rules have little impact
on the execution of programs.
Local variables must be declared with the var keyword, otherwise they will
become global variables.
Declarations on Top
It is good coding practice, to put all declarations at the top of each script or
function. This makes it easier to avoid unwanted (implied) global variables. It also
gives cleaner code, and reduces the possibility of unwanted re-declarations.
price = 19.90;
discount = 0.10;
Variable declarations should always be the be the first statements in scripts and
functions.
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.
Declaring numbers, strings, or booleans as objects, slows down execution speed, and
produces nasty side effects:
Example
var x = "John";
var y = new String("John");
(x === y) // is false because x is a string and y is an object.
Example
var x1 = {}; // new object
var x2 = ""; // new primitive string
var x3 = 0; // new primitive
number var x4 = false;
// new primitive boolean
var x5 = []; // new array object
var x6 = /()/; // new regexp object
var x7 = function(){}; // new function object
JavaScript is loosely typed. A variable can contain different data types, and a variable
can change its data type:
Example
var x = "Hello"; // typeof x is a string
x = 5; // changes typeof x to a number
Example
var x = 5 + 7; // x.valueOf() is 12, typeof x is a
number var x = 5 + "7"; // x.valueOf() is
57, typeof x is a string
var x = "5" + 7; // x.valueOf() is 57, typeof x is a
string var x = 5 - 7; // x.valueOf() is -2, typeof x is
a number var x = 5 - "7"; // x.valueOf() is -2,
typeof x is a number var x = "5" - 7; // x.valueOf()
is -2, typeof x is a number var x = 5 - "x"; //
x.valueOf() is NaN, typeof x is a number
Subtracting a string from a string, does not generate an error but returns NaN
(Not a Number):
Example
"Hello" - "Dolly" // returns NaN
Example
0 == ""; // true
1 == "1"; // true
1 == true; // true
Undefined values can break your code. It is a good habit to assign default
values to arguments.
Example
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}
function myFunction(x, y) {
y = y || 0;
}
if (x1 == 10)
This statement always returns true, because the assignment is always true:
if (x1 = 10)
Because of this, when adding a number as a number, will produce a different result
from adding a number as a string:
var x =
10; var y
= 5;
var z = x + y; // the result in z is 15
var x =
10; var y
= "5";
var z = x + y; // the result in z is "105"
Misunderstanding Floats
All numbers in JavaScript are stored as 64-bits Floating point numbers
(Floats).
All programming languages, including JavaScript, have difficulties with precise floating
point values:
var x =
0.1; var y
= 0.2;
var z = x + y // the result in z will not be
0.3 if (z == 0.3) // this if test will fail
Example 1
var x =
"Hello World!";
Example 2
var x =
"Hello
World!";
Example 3
var x =
"Hello \
World!";
Misplacing Semicolon
Because of a misplaced semicolon, this code block will execute regardless of the value of
x:
if (x == 19);
{
// code block
}
Because of this, these two examples will return the same result:
Example 1
function myFunction(a) {
var power = 10
return a * power
}
Example 2
function myFunction(a) {
var power = 10;
return a * power;
}
JavaScript will also allow you to break a statement into two lines.
Example 3
function myFunction(a) {
var
power = 10;
return a * power;
}
But, what will happen if you break the return statement in two lines like this:
Example 4
function myFunction(a) {
var
power = 10;
return
a * power;
}
The function will return undefined!
Example 5
function myFunction(a) {
var
power = 10;
return;
a * power;
}
Explanation
If a statement is incomplete like:
var
JavaScript will try to complete the statement by reading the next line:
power = 10;
return
return;
JavaScript will close the return statement at the end of the line, because it is a complete
statement.
Never break a return statement.
indexes.
Example:
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length; // person.length will return
3 var y = person[0]; // person[0] will return
"John"
If you use a named index, when accessing an array, JavaScript will redefine the array to a
standard object.
After the automatic redefinition, array methods and properties will produce undefined
or incorrect results:
Example:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length will return 0
var y = person[0]; // person[0] will return
undefined
Comma Incorrect:
points = [40, 100, 1, 5, 25, 10,];
Correct:
points = [40, 100, 1, 5, 25, 10];
Comma Incorrect:
person = {firstName:"John", lastName:"Doe", age:46,}
Correct:
person = {firstName:"John", lastName:"Doe", age:46}
If you want to test if an object exists, this will throw an error if the object is
undefined:
Incorrect:
if (myObj !== null && typeof myObj !== "undefined")
Correct:
if (typeof myObj !== "undefined" && myObj !== null)
Example:
for (var i = 0; i < 10; i++) {
// come code
}
return i;
JavaScript Performance
How to speed up your JavaScript code.
Every statement inside a loop will be executed for each iteration of the
the loop.
If you expect to access a DOM element several times, access it once, and use it as
a local variable:
Example
obj = document.getElementByID("demo");
obj.innerHTML = "Hello";
This will always improve page loading, and speed up rendering (page display), especially
on smaller devices.
Every attempt to search the DOM (like getElementsByTagName) is will benefit from a
smaller DOM.
Avoid Unnecessary Variables
Don't create new variables if you don't plan to save
With this:
While a script is downloading, the browser will not start any other
downloads. In addition all parsing and rendering activity might be
blocked.
The HTTP specification defines that browsers should not download more than two
components in parallel.
An alternative is to use defer="true" in the script tag. The defer attribute specifies
that the script should be executed before the page has finished parsing, but it only
works for external scripts.
If possible, you can add your script to the page by code, after the page has
loaded:
Example
<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).
Time passes, and we are now beginning to see complete support for ES5 in all
modern browsers.
JavaScript Reserved Words
In JavaScript you cannot use these reserved words as variables, labels, or
function names:
In HTML you must (for portability you should) avoid using the name of HTML and
Windows objects and properties:
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.
With the object model, JavaScript gets all the power it needs to create dynamic
HTML:
documents:
In other words: The HTML DOM is a standard for how to get, change, add, or
delete HTML elements.
HTML DOM methods are actions you can perform (on HTML Elements)
HTML DOM properties are values (of HTML Elements) that you can set or change
The DOM Programming Interface
The HTML DOM can be accessed with JavaScript (and with other
programming languages).
A property is a value that you can get or set (like changing the content of
an HTML element).
Example
The following example changes the content (the innerHTML) of the <p> element
with id="demo":
Example
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
In the example above the getElementById method used id="demo" to find the
element.
The innerHTML property can be used to get or change any HTML element,
including
<html> and <body>.
page. The document object is the owner of all other objects in your web
page.
If you want to access objects in an HTML page, you always start with accessing the
document object.
Below are some examples of how you can use the document object to
access and manipulate HTML.
The next chapters demonstrate the methods.
Later, in HTML DOM Level 3, more objects, collections, and properties were
added.
To do so, you have to find the elements first. There are a couple of ways to do
this:
Example
var x = document.getElementById("intro");
If the element is found, the method will return the element as an object
Example
var x = document.getElementById("main");
var y = x.getElementsByTagName("p");
method: document.getElementsByClassName("intro");
Finding elements by class name does not work in Internet Explorer 5,6,7, and 8.
Example
var x = document.getElementById("frm1");
var text = "";
var i;
for (i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
The following HTML objects (and object collections) are also accessible:
document.anchors
document.body
document.documentElement
document.embeds
document.forms
document.head
document.images
document.links
document.scripts
document.title
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>
Never use document.write() after the document is loaded. It will overwrite the
document.
syntax: document.getElementById(id).innerHTML =
new HTML
Example
<html>
<body>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>
</html>
This example changes the content of an <h1> element:
Example
<!DOCTYPE html>
<html>
<body>
<script>
var element = document.getElementById("header");
element.innerHTML = "New Header";
</script>
</body>
</html>
Example explained:
syntax: document.getElementById(id).attribute=new
value
This example changes the value of the src attribute of an <img> element:
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
Example explained:
syntax:
document.getElementById(id).style.property=new style
Example
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>
Using Events
The HTML DOM allows you to execute code when an event occurs.
Events are generated by the browser when "things happen" to HTML elements:
An element is clicked on
The page has loaded
Input fields are changed
You will learn more about events in the next chapter of this tutorial.
This example changes the style of the HTML element with id="id1", when the user clicks
a button:
Example
<!DOCTYPE html>
<html>
<body>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
Example
Mouse Over Me
Click Me
Reacting to Events
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML
element.
onclick=JavaScript
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<script>
function changeText(id)
{ id.innerHTML =
"Ooops!";
}
</script>
</body>
</html>
In the example above, a function named displayDate will be executed when the
button is clicked.
Example
Assign an onclick event to a button element:
<script>
document.getElementById("myBtn").onclick = function(){ displayDate() };
</script>
The onload event can be used to check the visitor's browser type and browser
version, and load the proper version of the web page based on the
information.
The onload and onunload events can be used to deal with cookies.
Example
<body onload="checkCookies()">
Example
<input type="text" id="fname" onchange="upperCase()">
Example
A simple onmouseover-onmouseout example:
Mouse Over Me
The onmousedown, onmouseup and onclick Events
The onmousedown, onmouseup, and onclick events are all parts of a mouse-click.
First when a mouse-button is clicked, the onmousedown event is triggered, then,
when the mouse-button is released, the onmouseup event is triggered, finally,
when the mouse- click is completed, the onclick event is triggered.
Example
A simple onmousedown-onmouseup example:
Click Me
method Example
Add an event listener that fires when a user clicks a button:
document.getElementById("myBtn").addEventListener("click", displayDate);
You can add many event handlers of the same type to one element, i.e two
"click" events.
You can add event listeners to any DOM object not only HTML elements. i.e the
window object.
The addEventListener() method makes it easier to control how the event reacts to
bubbling.
When using the addEventListener() method, the JavaScript is separated from the
HTML markup, for better readability and allows you to add event listeners even
when you do not control the HTML markup.
You can easily remove an event listener by using the removeEventListener() method.
Syntax
element.addEventListener(event, function, useCapture);
Note that you don't use the "on" prefix for the event; use "click" instead of
"onclick".
Example
Alert "Hello World!" when the user clicks on an element:
Example
Alert "Hello World!" when the user clicks on an element:
element.addEventListener("click", myFunction);
function myFunction()
{ alert ("Hello World!");
}
Example
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);
Example
element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);
Add an Event Handler to the Window Object
The addEventListener() method allows you to add event listeners on any HTML
DOM object such as HTML elements, the HTML document, the window object,
or other objects that supports events, like the xmlHttpRequest object.
Example
Add an event listener that fires when a user resizes the window:
window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = sometext;
});
Passing Parameters
When passing parameter values, use an "anonymous function" that calls the specified
function with the parameters:
Example
element.addEventListener("click", function(){ myFunction(p1, p2); });
Event propagation is a way of defining the element order when an event occurs.
If you have a <p> element inside a <div> element, and the user clicks on the <p>
element, which element's "click" event should be handled first?
In bubbling the inner most element's event is handled first and then the outer: the <p>
element's click event is handled first, then the <div> element's click event.
In capturing the outer most element's event is handled first and then the inner:
the
<div> element's click event will be handled first, then the <p> element's click event.
With the addEventListener() method you can specify the propagation type by
using the "useCapture" parameter:
The default value is false, which will use the bubbling propagation, when the value
is set to true, the event uses the capturing propagation.
Example
document.getElementById("myP").addEventListener("click", myFunction, true);
document.getElementById("myDiv").addEventListener("click", myFunction, true);
Example
element.removeEventListener("mousemove", myFunction);
Browser Support
The numbers in the table specifies the first browser version that fully supports these
methods.
Method
addEventListener() 1.0 9.0 1.0 1.0 7.0
removeEventListener() 1.0 9.0 1.0 1.0 7.0
Note: The addEventListener() and removeEventListener() methods are not supported in
IE 8 and earlier versions and Opera 7.0 and earlier versions. However, for these
specific browser versions, you can use the attachEvent() method to attach an
event handlers to the element, and the detachEvent() method to remove it:
element.attachEvent(event, function);
element.detachEvent(event, function);
Example
Cross-browser solution:
var x = document.getElementById("myBtn");
if (x.addEventListener) { // For all major browsers, except IE 8 and
earlier x.addEventListener("click", myFunction);
} else if (x.attachEvent) { // For IE 8 and earlier
versions x.attachEvent("onclick", myFunction);
}
DOM Nodes
According to the W3C HTML DOM standard, everything in an HTML document
is a node:
JavaScript. New nodes can be created, and all nodes can be modified
or deleted.
Node Relationships
The nodes in the node tree have a hierarchical relationship to each
other. The terms parent, child, and sibling are used to describe the
relationships.
In a node tree, the top node is called the root (or root node)
Every node has exactly one parent, except the root (which has no parent)
A node can have a number of children
Siblings (brothers or sisters) are nodes with the same parent
<html>
<head>
<title>DOM Tutorial</title>
</head>
<body>
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</body>
</html>
<html> and:
parentNode
childNodes[nodenumber]
firstChild
lastChild
nextSibling
previousSibling
Warning !
A common error in DOM processing is to expect an element node to contain
text.
In this example: <title>DOM Tutorial</title>, the element node <title> does not
contain text. It contains a text node with the value "DOM Tutorial".
The value of the text node can be accessed by the node's innerHTML property, or
the
nodeValue.
The following example collects the node value of an <h1> element and copies it into
a
<p> element:
Example
<html>
<body>
<p id="demo">Hello!</p>
<script>
var myText = document.getElementById("intro").childNodes[0].nodeValue;
document.getElementById("demo").innerHTML = myText;
</script>
</body>
</html>
In this tutorial we use the innerHTML property. However, learning the method
above is useful for understanding the tree structure and the navigation of the
DOM.
Example
<html>
<body>
<script>
myText = document.getElementById("intro").firstChild.nodeValue;
document.getElementById("demo").innerHTML = myText;
</script>
</body>
</html>
Example
<html>
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.body</b> property.</p>
</div>
<script>
alert(document.body.innerHTML);
</script>
</body>
</html>
Example
<html>
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the
<b>document.documentElement</b> property.</p>
</div>
<script>
alert(document.documentElement.innerHTML);
</script>
</body>
</html>
nodeName is read-only
nodeName of an element node is the same as the tag name
nodeName of an attribute node is the attribute name
nodeName of a text node is always #text
nodeName of the document node is always #document
Note: nodeName always contains the uppercase tag name of an HTML element.
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
To add text to the <p> element, you must create a text node first. This code
creates a text node:
element: para.appendChild(node);
element.appendChild(para);
If you don't want that you can use the insertBefore() method:
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>
Example Explained
This HTML document contains a <div> element with two child nodes (two
<p> elements):
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
parent.removeChild(child);
Here is a common workaround: Find the child you want to remove, and
use its parentNode property to find the parent:
Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
Example
var x = document.getElementsByTagName("p");
The nodes can be accessed by an index number. To access the second <p>
node you can write:
y = x[1];
Example
var myNodelist = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = myNodelist.length;
Example explained:
The length property is useful when you want to loop through the nodes in a
node list:
Example
Change the background color of all <p> elements in a node
document.getElementsByTagName("p");
var i;
for (i = 0; i < myNodelist.length; i++) {
myNodelist[i].style.backgroundColor = "red";
}
A node list may look like an array, but it is not. You can loop through the node
list and refer to its nodes like an array. However, you cannot use Array
Methods, like valueOf() or join() on the node list.
JavaScript Window - The Browser
Object Model
The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.
Since modern browsers have implemented (almost) the same methods and
properties for JavaScript interactivity, it is often referred to, as methods and properties
of the BOM.
All global JavaScript objects, functions, and variables automatically become members of
the window object.
Even the document object (of the HTML DOM) is a property of the window
object: window.document.getElementById("header");
document.getElementById("header");
Window Size
Three different properties can be used to determine the size of the browser
window (the browser viewport, NOT including toolbars and scrollbars).
document.documentElement.clientHeight
document.documentElement.clientWidth
or
document.body.clientHeight
document.body.clientWidth
Example
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
The example displays the browser window's height and width: (NOT including
toolbars/scrollbars)
Window Screen
The window.screen object can be written without the window
prefix. Properties:
screen.width
screen.height
screen.availWidth
screen.availHeight
screen.colorDepth
screen.pixelDepth
Example
Display the width of the screen in
screen.width
Example
Display the height of the screen in pixels:
Example
Display the available width of the screen in
Example
Display the available height of the screen in pixels:
Older computers used 16 bits, which gives a maximum of 65,536 different colors
("High Colors")
Very old computers, and old cell phones used 8 bits ("VGA colors").
Example
Display the color depth of the screen in
Example
Display the pixel depth of the screen in bits:
For modern computers, Color Depth and Pixel Depth are equal.
Window Location
The window.location object can be written without the window prefix.
Some examples:
window.location.href returns the href (URL) of the current page
window.location.hostname returns the domain name of the web host
window.location.pathname returns the path and filename of the current page
window.location.protocol returns the web protocol used (http:// or https://)
window.location.assign loads a new document
Example
Display the href (URL) of the current page:
Result is:
Example
Display the name of the host:
Result is:
Example
Display the path name of the current
/js/js_window_location.asp
Example
Display the web protocol:
Result is:
Example
Load a new document:
<html>
<head>
<script>
function newDoc() {
window.location.assign("http://www.w3schools.com")
}
</script>
</head>
<body>
</body>
</html>
Window History
The window.history object can be written without the window prefix.
To protect the privacy of the users, there are limitations to how JavaScript can access
this object.
Some methods:
Example
Create a back button on a page:
<html>
<head>
<script>
function goBack() {
window.history.back()
}
</script>
</head>
<body>
</body>
</html>
Example
Create a forward button on a page:
<html>
<head>
<script>
function goForward() {
window.history.forward()
}
</script>
</head>
<body>
</body>
</html>
Window Navigator
The window.navigator object can be written without the window prefix.
Some examples:
navigator.appName
navigator.appCodeName
navigator.platform
Navigator Cookie Enabled
The property cookieEnabled returns true if cookies are enabled, otherwise
false:
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Cookies Enabled is " + navigator.cookieEnabled;
</script>
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Name is " + navigator.appName + ". Code name is " + navigator.appCodeName;
</script>
Chrome, Firefox, IE, Safari, and Opera all return appCodeName "Mozilla".
The Browser Engine
The property product returns the engine name of the browser:
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.product;
</script>
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.appVersion;
</script>
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.userAgent;
</script>
Warning !!!
The information from the navigator object can often be misleading, and should
not be used to detect browser versions because:
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.platform;
</script>
The Browser Language
The property language returns the browser's language:
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.language;
</script>
Is Java Enabled?
The method javaEnabled() returns true if Java is enabled:
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = navigator.javaEnabled();
</script>
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
window.alert("sometext");
Example
alert("I am an alert box!");
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns
false.
Syntax
window.confirm("sometext");
Example
var r = confirm("Press a
button"); if (r == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
Prompt Box
A prompt box is often used if you want the user to input a value before entering
a page.
When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel"
the box returns null.
Syntax
window.prompt("sometext","defaultText");
Example
var person = prompt("Please enter your name", "Harry
Potter"); if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
Line Breaks
To display line breaks inside a popup box, use a back-slash followed by the
character n.
Example
alert("Hello\nHow are you?");
7
intervals. This is called timing events.
8
10
11
12
JavaScript Timing Events
With JavaScript, it is possible to execute some code at specified time-intervals. This is
called timing events.
It's very easy to time events in JavaScript. The two key methods that are used are:
Note: The setInterval() and setTimeout() are both methods of the HTML DOM
Window object.
Syntax
window.setInterval("javascript function", milliseconds);
The second parameter indicates the length of the time-intervals between each
execution.
Example
Alert "hello" every 3 seconds:
Below is an example that will display the current time. The setInterval() method is
used to execute the function once every 1 second, just like a digital watch.
Example
Display the current time:
function myTimer() {
var d = new
Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
Syntax
window.clearInterval(intervalVariable)
To be able to use the clearInterval() method, you must use a global variable
when creating the interval method:
Then you will be able to stop the execution by calling the clearInterval()
method.
Example
Same example as above, but we have added a "Stop time" button:
<p id="demo"></p>
<script>
var myVar = setInterval(function () {myTimer()}, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
The setTimeout() method will wait the specified number of milliseconds, and then
execute the specified function.
The second parameter indicates how many milliseconds, from now, you want to execute
the first parameter.
Example
Click a button. Wait 3 seconds. The page will alert "Hello":
Syntax
window.clearTimeout(timeoutVariable)
To be able to use the clearTimeout() method, you must use a global variable
when creating the timeout method:
Then, if the function has not already been executed, you will be able to
stop the execution by calling the clearTimeout() method.
Example
Same example as above, but with an added "Stop" button:
JavaScript Cookies
Cookies let you store user information in web pages.
Cookies were invented to solve the problem "how to remember information about
the user":
When a user visits a web page, his name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his
username=John Doe
When a browser request a web page from a server, cookies belonging to the
page is added to the request. This way the server gets the necessary data to
"remember" information about users.
document.cookie="username=John Doe";
You can also add an expiry date (in UTC time). By default, the cookie is deleted
when the browser is closed:
With a path parameter, you can tell the browser what path the cookie belongs
to. By default, the cookie belongs to the current page.
var x = document.cookie;
document.cookie will return all cookies in one string much like: cookie1=value;
cookie2=value; cookie3=value;
Note that you don't have to specify a cookie value when you delete a cookie.
Even if you write a whole cookie string to document.cookie, when you read it out
again, you can only see the name-value pair of it.
If you set a new cookie, older cookies are not overwritten. The new cookie is
added to document.cookie, so if you read document.cookie again you will get
something like:
cookie1=value; cookie2=value;
If you want to find the value of one specified cookie, you must write a
JavaScript function that searches for the cookie value in the cookie
string.
The first time a visitor arrives to the web page, he will be asked to fill in his
name. The name is then stored in a cookie.
The next time the visitor arrives at the same page, he will get a welcome
Example
function setCookie(cname, cvalue, exdays)
{ var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
Example explained:
The parameters of the function above are the name of the cookie (cname), the
value of the cookie (cvalue), and the number of days until the cookie should
expire (exdays).
The function sets a cookie by adding together the cookiename, the cookie
value, and the expires string.
Example
function getCookie(cname) {
var name = cname +
"=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
Function explained:
Create a variable (name) with the text to search for (cname + "=").
Loop through the ca array (i=0;i<ca.length;i++), and read out each value
c=ca[i]).
If the cookie is found (c.indexOf(name) == 0), return the value of the
cookie (c.substring(name.length,c.length).
If the cookie is not set, it will display a prompt box, asking for the name of the
user, and stores the username cookie for 365 days, by calling the setCookie
function:
Example
function checkCookie() {
var username=getCookie("username");
if (username!="") {
alert("Welcome again " + username);
}else{
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}
Example
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " +
expires;
}
function getCookie(cname) {
var name = cname +
"=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:",
""); if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
The example above runs the checkCookie() function when the page loads.