Javascript W 3 S
Javascript W 3 S
Example"
document.getElementById("demo").innerHTML = "Hello JavaScript";
Try it Yourself
Example
document.getElementById("demo").style.fontSize = "25px";
Try it Yourself
Example
<script>
</script>
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an
HTML page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
</script>
</head>
<body>
</body>
</html>
Try it Yourself
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an
HTML page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
</script>
</body>
</html>
Try it Yourself
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>
Try it yourself
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.
External scripts cannot contain <script> tags.
JavaScript Output
Previous
Next Chapter
JavaScript does NOT have any built-in print or display functions.
Writing
Writing
Writing
Writing
into
into
into
into
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>
Try it Yourself
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>
Try it Yourself
Using document.write() after an HTML document is fully loaded, will delete all
existing HTML:
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Try it Yourself
Using innerHTML
To access an HTML element, JavaScript can use the
document.getElementById(id) method.
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>
Try it Yourself
To "display data" in HTML, (in most cases) you will set the value of an
innerHTML property.
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
Previous
Next Chapter
JavaScript syntax is the set of rules, how JavaScript programs are
constructed.
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by the
computer.
In a programming language, these program instructions are called statements.
JavaScript is a programming language.
JavaScript statements are separated by semicolons.
Example
var x = 5;
var y = 6;
var z = x + y;
Try it Yourself
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
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:
Numbers are written with or without decimals:
10.50
1001
Try it Yourself
Strings are text, written within double or single quotes:
"John Doe"
'John Doe'
Try it Yourself
JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the var keyword to define variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value
6:
var x;
x = 6;
Try it Yourself
JavaScript Operators
JavaScript uses an assignment operator ( = ) to assign values to variables:
var x = 5;
var y = 6;
Try it Yourself
JavaScript uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10
Try it Yourself
JavaScript Expressions
An expression is a combination of values, variables, and operators, which
computes to a value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:
5 * 10
Try it Yourself
x * 10
Try it Yourself
The values can be of various types, such as numbers and strings.
For example, "John" + " " + "Doe", evaluates to "John Doe":
Try it Yourself
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
The var keyword tells the browser to create a new variable:
var x = 5 + 6;
var y = x * 10;
Try it Yourself
JavaScript Comments
var x = 5;
// var x = 6;
// I will be executed
Try it Yourself
JavaScript Identifiers
Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and
functions, and labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, an underscore (_), or a dollar
sign ($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
Numbers are not allowed as the first character.
This way JavaScript can easily distinguish identifiers from numbers.
lastName = "Doe";
lastname = "Peterson";
Try it Yourself
JavaScript does not interpret VAR or Var as the keyword var.
JavaScript Statements
Previous
Next Chapter
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
Try it Yourself
JavaScript Programs
Most JavaScript programs contain many JavaScript statements.
The statements are executed, one by one, in the same order as they are
written.
In this example, x, y, and z is given values, and finally z is displayed:
Example
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
Try it yourself
Semicolons ;
Semicolons separate JavaScript statements.
Add a semicolon at the end of each executable statement:
a = 5;
b = 6;
c = a + b;
Try it Yourself
When separated by semicolons, multiple statements on one line are allowed:
a = 5; b = 6; c = a + b;
Try it Yourself
JavaScript ignores multiple spaces. You can add white space to your script to
make it more readable.
The following lines are equivalent:
var person="Hege";
var x = y + z;
Example
document.getElementById("demo").innerHTML =
"Hello Dolly.";
Try it Yourself
Example
function myFunction() {
Try it Yourself
JavaScript Keywords
Description
break
continue
debugger
do ...
while
condition is true
for
function
Declares a function
if ... else
return
Exits a function
switch
try ...
catch
var
Declares a variable
JavaScript Comments
Previous
Next Chapter
JavaScript comments can be used to explain JavaScript code, and to make it
more readable.
JavaScript comments can also be used to prevent execution, when testing
alternative code.
This example uses a single line comment before each line, to explain the code:
Example
// Change heading:
// Change paragraph:
Try it yourself
This example uses a single line comment at the end of each line, to explain the
code:
Example
var x = 5;
var y = x + 2;
Try it yourself
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
This example uses a multi-line comment (a comment block) to explain the
code:
Example
/*
in my web page:
*/
Try it yourself
Example
//document.getElementById("myH").innerHTML = "My First Page";
Try it yourself
This example uses a comment block to prevent execution of multiple lines:
Example
/*
*/
Try it yourself
JavaScript Variables
Previous
Next Chapter
JavaScript Variables
JavaScript variables are containers for storing data values.
In this example, x, y, and z, are variables:
Example
var x = 5;
var y = 6;
var z = x + y;
Try it Yourself
From the example above, you can expect:
x stores the value 5
Example
var price1 = 5;
var price2 = 6;
Try it Yourself
In programming, just like in algebra, we use variables (like price1) to hold
values.
In programming, just like in algebra, we use variables in expressions (total =
price1 + price2).
From the example above, you can calculate the total to be 11.
JavaScript variables are containers for storing data values.
JavaScript Identifiers
x = x + 5
Example
var pi = 3.14;
Try it Yourself
var carName;
After the declaration, the variable has no value. (Technically it has the value of
undefined)
To assign a value to the variable, use the equal sign:
carName = "Volvo";
You can also assign a value to the variable when you declare it:
In the example below, we create a variable called carName and assign the value
"Volvo" to it.
Then we "output" the value inside an HTML paragraph with id="demo":
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = carName;
</script>
Try it yourself
Try it yourself
A declaration can span multiple lines:
carName = "Volvo",
price = 200;
Try it yourself
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.
A variable declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of this
statement:
Example
var carName;
Try it yourself
Example
var carName = "Volvo";
var carName;
Try it yourself
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using
operators like = and +:
Example
var x = 5 + 2 + 3;
Try it yourself
You can also add strings, but strings will be concatenated (added end-to-end):
Example
var x = "John" + " " + "Doe";
Try it Yourself
Also try this:
Example
var x = "5" + 2 + 3;
Try it Yourself
JavaScript Operators
Previous
Next Chapter
Example
Assign values to variables and add them together:
var x = 5;
var y = 2;
var z = x + y;
Try it yourself
Description
Addition
Subtraction
Multiplication
Division
Modulus
++
Increment
--
Decrement
Adding
var x = 5;
var y = 2;
var z = x + y;
Try it Yourself
The multiplication operator (*) multiplies numbers.
Multiplying
var x = 5;
var y = 2;
var z = x * y;
Try it Yourself
You will learn more about JavaScript operators in the next chapters.
Example
Same As
x=y
x=y
+=
x += y
x=x+y
-=
x -= y
x=x-y
*=
x *= y
x=x*y
/=
x /= y
x=x/y
%=
x %= y
x=x%y
Assignment
var x = 10;
Try it Yourself
The addition assignment operator (+=) adds a value to a variable.
Assignment
var x = 10;
x += 5;
Try it Yourself
Example
txt1 = "John";
txt2 = "Doe";
John Doe
Try it Yourself
The += assignment operator can also be used to add (concatenate) strings:
Example
txt1 = "What a very ";
Try it Yourself
Example
x = 5 + 5;
y = "5" + 5;
z= "Hello" + 5;
10
55
Hello5
Try it Yourself
The rule is: If you add a number and a string, the result will be a string!
Description
tor
==
equal to
===
!=
not equal
!==
>
greater than
<
less than
>=
<=
JavaScript Arithmetic
Previous
Next Chapter
A typical thing to do with numbers is arithmetic.
Description
Addition
Subtraction
Multiplication
Division
Modulus
++
Increment
--
Decrement
Arithmetic Operations
A typical arithmetic operation operates on two numbers.
The two numbers can be literals:
Example
var x = 100 + 50;
Try it Yourself
or variables:
Example
var x = a + b;
Try it Yourself
or expressions:
Example
var x = (100 + 50) * a;
Try it Yourself
100
Operator
Operand
50
Adding
var x = 5;
var y = 2;
var z = x + y;
Try it Yourself
The subtraction operator (-) subtracts numbers.
Subtracting
var x = 5;
var y = 2;
var z = x - y;
Try it Yourself
The multiplication operator (*) multiplies numbers.
Multiplying
var x = 5;
var y = 2;
var z = x * y;
Try it Yourself
The division operator (/) divides numbers.
Dividing
var x = 5;
var y = 2;
var z = x / y;
Try it Yourself
The modular operator (%) returns the division remainder.
Modulus
var x = 5;
var y = 2;
var z = x % y;
Try it Yourself
The increment operator (++) increments numbers.
Incrementing
var x = 5;
x++;
var z = x;
Try it Yourself
The decrement operator (--) decrements numbers.
Decrementing
var x = 5;
x--;
var z = x;
Try it Yourself
Operator Precedence
Operator precedence describes the order in which operations are performed in
an arithmetic expression.
Example
var x = 100 + 50 * 3;
Try it Yourself
Is the result of example above the same as 150 * 3, or is it the same as 100 +
150?
Is the addition or the multiplication done first?
As in traditional school mathematics, the multiplication is done first.
Multiplication (*) and division (/) have higher precedence than addition (+)
and subraction (-).
And (as in school mathematics) the precedence can be changed by using
parentheses:
Example
var x = (100 + 50) * 3;
Try it Yourself
When using parentheses, the operations inside the parentheses are computed
first.
When many operations have the same precedence (like addition and
subtraction), they are computed from left to right:
Example
var x = 100 + 50 - 3;
Try it Yourself
Precedence
()
Expression grouping
++ --
*/%
+-
JavaScript Assignment
Previous
Next Chapter
Example
Same As
x=y
x=y
+=
x += y
x=x+y
-=
x -= y
x=x-y
*=
x *= y
x=x*y
/=
x /= y
x=x/y
%=
x %= y
x=x%y
Assignment
var x = 10;
Try it Yourself
The += assignment operator adds a value to a variable.
Assignment
var x = 10;
x += 5;
Try it Yourself
The -= assignment operator subtracts a value from a variable.
Assignment
var x = 10;
x -= 5;
Try it Yourself
The *= assignment operator multiplies a variable.
Assignment
var x = 10;
x *= 5;
Try it Yourself
The /= assignment divides a variable.
Assignment
var x = 10;
x /= 5;
Try it Yourself
The %= assignment operator assigns a remainder to a variable.
Assignment
var x = 10;
x %= 5;
Try it Yourself
// Number
// String
// Array
// Object
var x = 16 + "Volvo";
Does it make any sense to add "Volvo" to sixteen? Will it produce a result? Will
it produce an error?
JavaScript will treat the example above as:
If the second operand is a string, JavaScript will also treat the first
operand as a string.
Example
var x = 16 + "Volvo";
Try it Yourself
JavaScript evaluates expressions from left to right. Different sequences can
produce different results:
JavaScript:
var x = 16 + 4 + "Volvo";
Result:
20Volvo
Try it Yourself
JavaScript:
var x = "Volvo" + 16 + 4;
Result:
Volvo164
Try it Yourself
In the first example, JavaScript treats 16 and 4 as numbers, until it reaches
"Volvo".
In the second example, since the first operand is a string, all operands are
treated as strings.
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
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";
double quotes
double quotes
single quotes
Try it yourself
You will learn more about strings later in this tutorial.
JavaScript Numbers
JavaScript has only one type of numbers.
Numbers can be written with, or without decimals:
Example
var x1 = 34.00;
var x2 = 34;
Extra large or extra small numbers can be written with scientific (exponential)
notation:
Example
var y = 123e5;
// 12300000
var z = 123e-5;
// 0.00123
Try it yourself
You will learn more about numbers later in this tutorial.
JavaScript Booleans
Booleans can only have two values: true or false.
Example
var x = true;
var y = false;
JavaScript Arrays
JavaScript arrays are written with square brackets.
Array items are separated by commas.
The following code declares (creates) an array called cars, containing three
items (car names):
Example
var cars = ["Saab", "Volvo", "BMW"];
Try it Yourself
Array indexes are zero-based, which means the first item is [0], second is [1],
and so on.
You will learn more about arrays later in this tutorial.
JavaScript Objects
JavaScript objects are written with curly braces.
Object properties are written as name:value pairs, separated by commas.
Example
Try it Yourself
The object (person) in the example above has 4 properties: firstName,
lastName, age, and eyeColor.
You will learn more about objects later in this tutorial.
Example
typeof "John"
// Returns string
typeof 3.14
// Returns number
typeof false
// Returns boolean
typeof [1,2,3,4]
// Returns object
Try it Yourself
Undefined
In JavaScript, a variable without a value, has the value undefined. The typeof
is also undefined.
Example
var person;
undefined
Try it Yourself
Any variable can be emptied, by setting the value to undefined. The type will
also be undefined.
Example
person = undefined;
undefined
Try it Yourself
Empty Values
An empty value has nothing to do with undefined.
An empty string variable has both a value and a type.
Example
var car = "";
string
Try it Yourself
Null
In JavaScript null is "nothing". It is supposed to be something that doesn't exist.
Unfortunately, in JavaScript, the data type of null is an object.
You can consider it a bug in JavaScript that typeof null is an object. It
should be null.
You can empty an object by setting it to null:
Example
var person = null;
an object
Try it Yourself
You can also empty an object by setting it to undefined:
Example
var person = undefined;
undefined
Try it Yourself
// undefined
typeof null
// object
// false
null == undefined
// true
Try it Yourself
JavaScript Functions
Previous
Next Chapter
A JavaScript function is a block of code designed to perform a particular
task.
A JavaScript function is executed when "something" invokes it (calls it).
Example
function myFunction(p1, p2) {
return p1 * p2;
product of p1 and p2
Try it yourself
code to be executed
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
You will learn a lot more about function invocation later in this tutorial.
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute
the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to
the "caller":
Example
Calculate the product of two numbers, and return the result:
function myFunction(a, b) {
return a * b;
of a and b
12
Try it yourself
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) {
document.getElementById("demo").innerHTML = toCelsius(77);
Try it yourself
Example
function toCelsius(fahrenheit) {
document.getElementById("demo").innerHTML = toCelsius;
Try it Yourself
Example
You can use:
Instead of:
var x = toCelsius(32);
Try it Yourself
You will learn a lot more about functions later in this tutorial.
Exercise 2
Exercise 3
Exercise 4
Exercise 5
JavaScript Objects
Previous
Next Chapter
Properties
Methods
car.name = Fiat
car.start()
car.model = 500
car.drive()
car.weight =
car.brake()
850kg
car.stop()
car.color = white
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:
Try it Yourself
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
Try it Yourself
The values are written as name:value pairs (name and value separated by a
colon).
JavaScript objects are containers for named values.
Object Properties
The name:values pairs (in JavaScript objects) are called properties.
Property
Property Value
firstName
John
lastName
Doe
age
50
eyeColor
blue
Object Methods
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
Property
Property Value
firstName
John
lastName
Doe
age
50
eyeColor
blue
fullName
Object Definition
You define (and create) a JavaScript object with an object literal:
Example
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
Try it Yourself
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"
};
Try it Yourself
objectName.propertyName
or
objectName["propertyName"]
Example1
person.lastName;
Try it Yourself
Example2
person["lastName"];
Try it Yourself
objectName.methodName()
Example
name = person.fullName();
Try it Yourself
If you access the fullName property, without (), it will return the function
definition:
Example
name = person.fullName;
Try it Yourself
//
Avoid String, Number, and Boolean objects. They complicate your code and slow
down execution speed.
You will learn more about objects later in this tutorial.
Exercise 2
Exercise 3
JavaScript Scope
Previous
Next Chapter
JavaScript Scope
In JavaScript, objects and functions are also variables.
In JavaScript, scope is the set of variables, objects, and functions you
have access to.
JavaScript has function scope: The scope changes inside functions.
Example
// code here can not use carName
function myFunction() {
Try it Yourself
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.
Example
var carName = " Volvo";
function myFunction() {
Try it Yourself
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";
Try it Yourself
Function Arguments
Function arguments (parameters) work as local variables inside functions.
Example
// code here can use window.carName
function myFunction() {
carName = "Volvo";
Try it Yourself
JavaScript Events
Previous
Next Chapter
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 does.
Here are some examples of HTML events:
An HTML web page has finished loading
An HTML input field was changed
An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be added to
HTML elements.
With single quotes:
Exampleo
<button onclick='getElementById("demo").innerHTML=Date()'>The
time is?</button>
Try it Yourself
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 its own element (using
this.innerHTML):
Example
<button onclick="this.innerHTML=Date()">The time is?</button>
Try it Yourself
Example
<button onclick="displayDate()">The time is?</button>
Try it Yourself
Event
Description
onchange
onclick
onmouseover
onmouseout
onkeydown
onload
The list is much longer: W3Schools JavaScript Reference HTML DOM Events.
Exercise 2
Exercise 3
JavaScript Strings
Previous
Next Chapter
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";
Try it Yourself
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";
Try it Yourself
String Length
The length of a string is found in the built in property length:
Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Try it Yourself
Special Characters
Because strings must be written within quotes, JavaScript will misunderstand
this string:
Example
var x = 'It\'s alright';
Try it Yourself
The escape character (\) can also be used to insert other special characters in a
string.
This is the list 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.";
Try it Yourself
You can also break up a code line within a text string with a single backslash:
Example
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
Try it Yourself
Example
document.getElementById("demo").innerHTML = "Hello" +
"Dolly!";
Try it Yourself
You cannot break up a code line with a backslash:
Example
document.getElementById("demo").innerHTML = \
"Hello Dolly!";
Try it Yourself
Example
var x = "John";
Try it Yourself
Example
var x = "John";
Try it Yourself
When using the === equality operator, equal strings are not equal, because the
=== operator expects equality in both type and value.
Example
var x = "John";
Try it Yourself
Or even worse. Objects cannot be compared:
Example
var x = new String("John");
Try it Yourself
String Properties
Property
constructor
Description
length
prototype
String Methods
Method
Description
charAt()
charCodeAt()
concat()
fromCharCode()
indexOf()
lastIndexOf()
localeCompare()
match()
replace()
search()
slice()
split()
substr()
substring()
toLocaleLowerCa
se()
host's locale
toLocaleUpperCa
se()
host's locale
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()
Exercise 2
Exercise 3
Exercise 4
Example
var str = "Please locate where 'locate' occurs!";
Try it Yourself
The lastIndexOf() method returns the index of the last occurrence of a
specified text in a string:
Example
Try it Yourself
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not
found.
JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third ...
Both methods accept a second parameter as the starting position for the search.
Example
var str = "Please locate where 'locate' occurs!";
Try it Yourself
Example
var str = "Apple, Banana, Kiwi";
Banana
Try it yourself
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";
Banana
Try it Yourself
If you omit the second parameter, the method will slice out the rest of the
string:
Example
Try it Yourself
or, counting from the end:
Example
var res = str.slice(-12);
Try it Yourself
Example
var str = "Apple, Banana, Kiwi";
Banana
Try it yourself
If you omit the second parameter, substring() will slice out the rest of the
string.
Example
var str = "Apple, Banana, Kiwi";
Banana
Try it yourself
If the first parameter is negative, the position counts from the end of the string.
The second parameter can not be negative, because it defines the length.
If you omit the second parameter, substr() will slice out the rest of the string.
Example
str = "Please visit Microsoft!";
var n = str.replace("Microsoft","W3Schools");
Try it Yourself
The replace() method can also take a regular expression as the search value.
Example
var text1 = "Hello World!";
// String
upper
Try it Yourself
A string is converted to lower case with toLowerCase():
Example
var text1 = "Hello World!";
// String
lower
Try it Yourself
Example
var text1 = "Hello";
text3 = text1.concat("
",text2);
Try it Yourself
The concat() method can be used instead of the plus operator. These two lines
do the same:
Example
var text = "Hello" + " " + "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.
Example
str.charAt(0);
// returns H
Try it Yourself
Example
var str = "HELLO WORLD";
str.charCodeAt(0);
// returns 72
Try it Yourself
str[0];
// returns H
Example
var txt = "a,b,c,d,e";
txt.split(",");
// String
// Split on commas
txt.split(" ");
// Split on spaces
txt.split("|");
// Split on pipe
Try it Yourself
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
Try it Yourself
JavaScript Numbers
Previous
Next Chapter
JavaScript Numbers
JavaScript numbers can be written with, or without decimals:
Example
var x = 34.00;
var y = 34;
Extra large or extra small numbers can be written with scientific (exponent)
notation:
Example
var x = 123e5;
// 12300000
var y = 123e-5;
// 0.00123
Unlike many other programming languages, JavaScript does not define different
types of numbers, like integers, short, long, floating-point etc.
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:
Value (aka Fraction/Mantissa)
52 bits (0 - 51)
Exponent
Sign
1 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
Try it Yourself
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
Try it yourself
To solve the problem above, it helps to multiply and divide:
Example
var x = (0.2 * 10 + 0.1 * 10) / 10;
// x will be 0.3
Try it Yourself
Hexadecimal
JavaScript interprets numeric constants as hexadecimal if they are preceded by
0x.
Example
var x = 0xFF;
// x will be 255
Try it Yourself
Example
var myNumber = 128;
myNumber.toString(16);
// returns 80
myNumber.toString(8);
// returns 200
myNumber.toString(2);
// returns 10000000
Try it Yourself
Infinity
Infinity (or -Infinity) is the value JavaScript will return if you calculate a number
outside the largest possible number.
Example
var myNumber = 2;
Try it yourself
Division by 0 (zero) also generates Infinity:
Example
var x =
2 / 0;
var y = -2 / 0;
// x will be Infinity
// y will be -Infinity
Try it Yourself
Infinity is a number: typeOf Infinity returns number.
Example
typeof Infinity;
// returns "number"
Try it Yourself
Example
var x = 100 / "Apple";
Try it Yourself
However, if the string contains a numeric value , the result will be a number:
Example
var x = 100 / "10";
// x will be 10
Try it Yourself
You can use the global JavaScript function isNaN() to find out if a value is a
number.
Example
var x = 100 / "Apple";
isNaN(x);
Try it Yourself
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
Try it Yourself
Or the result might be a concatenation:
Example
var x = NaN;
var y = "5";
var z = x + y;
// z will be NaN5
Try it Yourself
NaN is a number, and typeof NaN returns number:
Example
typeof NaN;
// returns "number"
Try it Yourself
Example
var x = 123;
Try it yourself
Don't create Number objects. They slow down execution speed, and
produce nasty side effects:
When using the == equality operator, equal numbers looks equal:
Example
var x = 500;
Try it Yourself
When using the === equality operator, equal numbers are not equal, because
the === operator expects equality in both type and value.
Example
var x = 500;
Try it Yourself
Or even worse. Objects cannot be compared:
Example
var x = new Number(500);
Try it Yourself
Number Properties
Property
Description
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINI
TY
NaN
POSITIVE_INFINI
TY
Example
var x = Number.MAX_VALUE;
Try it yourself
Number properties belongs to the JavaScript's number object wrapper called
Number.
These properties can only be accessed as Number.MAX_VALUE.
Using myNumber.MAX_VALUE, where myNumber is a variable, expression, or
value, will return undefined:
Example
var x = 6;
var y = x.MAX_VALUE;
// y becomes undefined
Try it yourself
Exercise 2
Exercise 3
Exercise 4
Previous
Next Chapter
Number methods help you to work with numbers.
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()
parseFloat()
parseInt()
Number Methods
JavaScript number methods are methods that can be used on numbers:
Method
Description
toString()
toExponential()
toFixed()
toPrecision()
valueOf()
All number methods return a new value. They do not change the original
variable.
Example
var x = 123;
x.toString();
(123).toString();
(100 + 23).toString();
Try it Yourself
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
Try it yourself
The parameter is optional. If you don't specify it, JavaScript will not round the
number.
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
Try it yourself
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
Try it Yourself
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
Try it Yourself
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
Try it yourself
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
Try it yourself
If the number cannot be converted, NaN (Not a Number) is returned.
Example
var x = 123;
x.valueOf();
(123).valueOf();
(100 + 23).valueOf();
Try it Yourself
In JavaScript, a number can be a primitive value (typeof = number) or an
object (typeof = object).
The valueOf() method is used internally in JavaScript to convert Number objects
to primitive values.
There is no reason to use it in your code.
In JavaScript, all data types have a valueOf() and a toString() method.
Example
Math.random();
Try it yourself
Example
// returns -200
Try it yourself
Example
Math.max(0, 150, 30, 20, -8, -200);
// returns 150
Try it yourself
Math.random()
Math.random() returns a random number between 0 (inclusive), and 1
(exclusive):
Example
Math.random();
Try it Yourself
Math.round()
Math.round() rounds a number to the nearest integer:
Example
Math.round(4.7);
// returns 5
Math.round(4.4);
// returns 4
Try it Yourself
Math.ceil()
Math.ceil() rounds a number up to the nearest integer:
Example
Math.ceil(4.4);
// returns 5
Try it Yourself
Math.floor()
Math.floor() rounds a number down to the nearest integer:
Example
Math.floor(4.7);
// returns 4
Try it Yourself
Math.floor() and Math.random() can be used together to return a random
number between 0 and 10:
Example
Math.floor(Math.random() * 11);
between 0 and 10
Try it Yourself
Math Constants
JavaScript provides 8 mathematical constants that can be accessed with the
Math object:
Example
Math.E
Math.PI
// returns PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
Try it yourself
Description
abs(x)
acos(x)
asin(x)
atan(x)
atan2(y,x)
ceil(x)
cos(x)
exp(x)
floor(x)
log(x)
max(x,y,z,...,
n)
min(x,y,z,...,
n)
pow(x,y)
random()
round(x)
sin(x)
sqrt(x)
tan(x)
Exercise 2
Exercise 3
Exercise 4
JavaScript Dates
Previous
Next Chapter
The Date object lets you work with dates (years, months, days, hours,
minutes, seconds, and milliseconds)
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>
Try it Yourself
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.
new Date()
new Date(milliseconds)
new Date(dateString)
Using new Date(), creates a new date object with the current date and time:
Example
<script>
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself
Using new Date(date string), creates a new date object from the specified
date and time:
Example
<script>
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself
Valid date strings (date formats) are described in the next chapter.
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>
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself
Example
<script>
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself
Variants of the example above let us omit any of the last 4 parameters:
Example
<script>
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself
Date Methods
When a Date object is created, a number of methods allow you to operate on
it.
Date methods allow you to get and set the year, month, day, hour, minute,
second, and millisecond of objects, using either local time or UTC (universal, or
GMT) time.
Date methods are covered in a later chapter.
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>
Try it Yourself
The toUTCString() method converts a date to a UTC string (a date display
standard).
Example
<script>
document.getElementById("demo").innerHTML = d.toUTCString();
</script>
Try it Yourself
The toDateString() method converts a date to a more readable format:
Example
<script>
document.getElementById("demo").innerHTML = d.toDateString();
</script>
Try it Yourself
Date objects are static, not dynamic. The computer time is ticking, but
date objects, once created, are not.
Exercise 2
Exercise 3
Example
var d = new Date("2015-03-25");
Try it Yourself
Or as: "2015-12" (YYYY-MM):
Example
var d = new Date("2015-03");
Try it Yourself
Or as "2015" (YYYY):
Example
var d = new Date("2015");
Try it Yourself
Or as "2015-12-24T12:00:00":
Example
var d = new Date("2015-03-25T12:00:00");
Try it Yourself
The T in the date string, between the date and time, indicates UTC time.
Example
var d = new Date("Mar 25 2015");
Try it Yourself
But, year, month, and day can be in any order:
Example
var d = new Date("25 Mar 2015");
Try it Yourself
Example
var d = new Date("2015 Mar 25");
Try it Yourself
And, month can be written in full (January), or abbreviated (Jan):
Example
var d = new Date("January 25 2015");
Try it Yourself
Example
var d = new Date("Jan 25 2015");
Try it Yourself
Commas are ignored. Names are case insensitive:
Example
var d = new Date("2015, JANUARY, 25");
Try it Yourself
Short dates are most often written with an "MM/DD/YYYY" syntax like this:
Example
var d = new Date("03/25/2015");
Try it Yourself
Either "/" or "-" can be used as a separator:
Example
var d = new Date("03-25-2015");
Try it Yourself
JavaScript will also accept "YYYY/MM/DD":
Example
var d = new Date("2015/03/25");
Try it Yourself
Month is written before day in all short date and ISO date formats.
Full Format
JavaScript will accept date strings in "full JavaScript format":
Example
var d = new Date("Wed Mar 25 2015 09:56:24 GMT+0100 (W. Europe
Standard Time)");
Try it Yourself
JavaScript will ignore errors both in the day name and in the time parentheses:
Example
var d = new Date("Fri Mar 25 2015 09:56:24 GMT+0100 (Tokyo
Time)");
Try it Yourself
Date methods let you get and set date values (years, months, days, hours,
minutes, seconds, milliseconds)
Description
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
Example
<script>
document.getElementById("demo").innerHTML = d.getTime();
</script>
Try it Yourself
Example
<script>
document.getElementById("demo").innerHTML = d.getFullYear();
</script>
Try it Yourself
Example
<script>
document.getElementById("demo").innerHTML = d.getDay();
</script>
Try it Yourself
In JavaScript, the first of the week (0) means "Sunday", even if some
countries in the world consider the first day of the week to be "Monday".
You can use an array of names, and getDay() to return the weekday as a name:
Example
<script>
var days =
["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Sat
urday"];
document.getElementById("demo").innerHTML = days[d.getDay()];
</script>
Try it Yourself
Method
Description
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
Example
<script>
d.setFullYear(2020, 0, 14);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself
Example
<script>
d.setDate(20);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself
The setDate() method can also be used to add days to a date:
Example
<script>
d.setDate(d.getDate() + 50);
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself
If adding days, shifts the month or year, the changes are handled
automatically by the Date object.
If you have a valid date string, you can use the Date.parse() method to
convert it to milliseconds.
Date.parse() returns the number of milliseconds between the date and
January 1, 1970:
Example
<script>
document.getElementById("demo").innerHTML = msec;
</script>
Try it Yourself
You can then use the number of milliseconds to convert it to a date object:
Example
<script>
document.getElementById("demo").innerHTML = d;
</script>
Try it Yourself
Compare Dates
Dates can easily be compared.
The following example compares today's date with January 14, 2100:
Example
var today, someday, text;
someday.setFullYear(2100, 0, 14);
} else {
document.getElementById("demo").innerHTML = text;
Try it Yourself
JavaScript Arrays
Previous
Next Chapter
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>
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"];
Try it Yourself
Spaces and line breaks are not important. A declaration can span multiple lines:
Example
var cars = [
"Saab",
"Volvo",
"BMW"
];
Try it Yourself
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:
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
Example
var cars = new Array("Saab", "Volvo", "BMW");
Try it Yourself
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.
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Array:
var person = ["John", "Doe", 46];
Try it Yourself
Objects use names to access its "members". In this example, person.firstName
returns John:
Object:
var person = {firstName:"John", lastName:"Doe", age:46};
Try it Yourself
Examples
var x = cars.length;
var y = cars.sort();
alphabetical order
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length;
Try it Yourself
The length property is always one more than the highest array index.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon");
to fruits
Try it Yourself
New element can also be added to an array using the length property:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon";
(Lemon) to fruits
Try it Yourself
Adding elements with high indexes can create undefined "holes" in an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[10] = "Lemon";
(Lemon) to fruits
Try it Yourself
Example
var index;
for
text += fruits[index];
Try it Yourself
Associative Arrays
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
Example
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length;
var y = person[0];
Try it Yourself
WARNING !!
If you use a named index, JavaScript will redefine the array to a standard
object.
After that, all array methods and properties will produce incorrect
results.
Example:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length;
var y = person[0];
Try it Yourself
// Bad
// Good
These two different statements both create a new array containing 6 numbers:
// Bad
// Good
Try it Yourself
The new keyword complicates your code and produces nasty side effects:
Try it Yourself
typeof fruits;
Try it Yourself
The typeof operator returns object because a JavaScript array is an object.
To solve this problem you can create your own isArray() function:
function isArray(myArray) {
Try it Yourself
The function above always returns true if the argument is an array.
Or more precisely: it returns true if the object prototype of the argument is
"[object array]".
Exercise 2
Exercise 3
Exercise 4
Exercise 5
Previous
Next Chapter
The strength of JavaScript arrays lies in the array methods.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.valueOf();
Try it Yourself
For JavaScript arrays, valueOf() and toString() are equal.
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Try it Yourself
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>
</script>
Try it Yourself
Popping
The pop() method removes the last element from an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
from fruits
Try it Yourself
The pop() method returns the value that was "popped out":
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.pop();
Try it Yourself
Pushing
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");
//
fruits
Try it Yourself
The push() method returns the new array length:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.push("Kiwi");
//
the value of x is 5
Try it Yourself
Shifting Elements
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
from fruits
Try it Yourself
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");
fruits
Try it Yourself
The shift() method returns the string that was "shifted out".
The unshift() method returns the new array length.
Changing Elements
Array elements are accessed using their index number:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi";
to "Kiwi"
Try it Yourself
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";
fruit
Try it Yourself
// Appends "Kiwi" to
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];
fruits to undefined
Try it Yourself
Using delete on array elements leaves undefined holes in the array. Use
pop() or shift() instead.
Splicing an Array
The splice() method can be used to add new items to an array:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
Try it Yourself
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);
fruits
Try it Yourself
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
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
Try it Yourself
Reversing an Array
The reverse() method reverses the elements in an array.
You can use it to sort an array in descending order:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
Try it Yourself
Numeric Sort
By default, the sort() function sorts values as strings.
This works well for strings ("Apple" comes before "Banana").
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.
You can fix this by providing a compare function:
Example
var points = [40, 100, 1, 5, 25, 10];
Try it Yourself
Use the same trick to sort an array descending:
Example
var points = [40, 100, 1, 5, 25, 10];
Try it Yourself
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
function(40,100).
The function calculates 40-100, and returns -60 (a negative value).
The sort function will sort 40 as a value lower than 100.
Example
var points = [40, 100, 1, 5, 25, 10];
Try it Yourself
And the lowest:
Example
var points = [40, 100, 1, 5, 25, 10];
Try it Yourself
Joining Arrays
The concat() method creates a new array by concatenating two arrays:
Example
var myGirls = ["Cecilie", "Lone"];
// Concatenates
Try it Yourself
The concat() method can take any number of array arguments:
Example
var arr1 = ["Cecilie", "Lone"];
// Concatenates
Try it Yourself
Slicing an Array
The slice() method slices out a piece of an array into a new array:
Example
Try it Yourself
The slice() method selects elements starting at the start argument, and ends at,
but does not include, the end argument.
If the end argument is omitted, the slice() method slices out the rest of the
array:
Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
Try it Yourself
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)
10 > 9
Try it yourself
Description
Example
ator
==
equal to
if (day == "Monday")
>
greater than
<
less than
3.14
-15
"Hello"
"false"
7 + 1 + 3.14
5 < 6
Try it yourself
var x = 0;
Boolean(x);
// returns false
Try it yourself
var x = -0;
Boolean(x);
// returns false
Try it yourself
var x = "";
Boolean(x);
// returns false
Try it yourself
var x;
Boolean(x);
// returns false
Try it yourself
var x = null;
Boolean(x);
// returns false
Try it yourself
var x = false;
Boolean(x);
// returns false
Try it yourself
var x = 10 / "H";
Boolean(x);
// returns false
Try it yourself
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:
Opera
Description
tor
==
===
equal to
Comparin
Return
Try it
x == 8
false
Try it
x == 5
true
Try it
x == "5"
true
Try it
x === 5
true
Try it
x === "5"
false
Try it
!=
not equal
x != 8
true
Try it
!==
x !== "5"
true
Try it
x !== 5
false
Try it
type
>
greater than
x>8
false
Try it
<
less than
x<8
true
Try it
>=
x >= 8
false
Try it
<=
x <= 8
true
Try it
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:
Opera
Description
Example
Try it
tor
&&
and
Try it
||
or
(x == 5 || y == 5) is false
Try it
not
!(x == y) is true
Try it
Syntax
variablename = (condition) ? value1:value2
Example
var voteable = (age < 18) ? "Too young":"Old enough";
Try it Yourself
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".
age = Number(age);
if (isNaN(age)) {
} else {
Try it Yourself
Example
x = 5 & 1;
The result in x:
Try it Yourself
Opera
Description
Example
Same as
Result
Decimal
tor
&
AND
x=5&1
0001
OR
x=5|1
0101 | 0001
0101
NOT
x=~5
1010
10
XOR
x=5^1
0101 ^ 0001
0100
<<
Left shift
x = 5 << 1
0101 << 1
1010
10
>>
Right shift
x = 5 >> 1
0101 >> 1
0010
~0101
The examples above uses 4 bits unsigned examples. But JavaScript uses
32-bit signed numbers.
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 this.
In JavaScript we have the following conditional statements:
Use
Use
Use
Use
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
}
Example
Make a "Good day" greeting if the hour is less than 18:00:
Good day
Try it yourself
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 hour is less than 18, create a "Good day" greeting, otherwise "Good
evening":
} else {
Good day
Try it yourself
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":
} else {
Good day
Try it yourself
More Examples
Random link
This example will write a link to either W3Schools or to the World Wildlife
Foundation (WWF). By using a random number, there is a 50% chance for each
of the links.
Syntax
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
Example
The getDay() method returns the weekday as a number between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
Use the weekday number to calculate weekday name:
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
Monday
Try it yourself
When the JavaScript code interpreter reaches a break keyword, it breaks out of
the switch block.
This will stop the execution of more code and 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
The getDay() method returns the weekday as a number between 0 and 6.
If today is neither Saturday (6) nor Sunday (0), write a default message:
case 6:
break;
case 0:
break;
default:
Try it yourself
Example
switch (new Date().getDay()) {
case 1:
case 2:
case 3:
default:
break;
case 4:
case 5:
break;
case 0:
case 6:
Try it yourself
If default is not the last case in the switch block, remember to end it with
a break.
Exercise 2
Exercise 3
Exercise 4
JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each
time with a different value.
Often this is the case when working with arrays:
Instead of writing:
text += cars[0] + "<br>";
Try it Yourself
Example
for (i = 0; i < 5; i++) {
Try it yourself
From the example above, you can read:
Statement 1
Normally you will use statement 1 to initiate the variable used in the loop (i =
0).
This is not always the case, JavaScript doesn't care. Statement 1 is optional.
You can initiate many values in statement 1 (separated by comma):
Example
for (i = 0, len = cars.length, text = ""; i < len; i++) {
Try it Yourself
And you can omit statement 1 (like when your values are set before the loop
starts):
Example
var i = 2;
Try it Yourself
Statement 2
Often statement 2 is used to evaluate the condition of the initial variable.
This is not always the case, JavaScript doesn't care. Statement 2 is also
optional.
If statement 2 returns true, the loop will start over again, if it returns false, the
loop will end.
If you omit statement 2, you must provide a break inside the loop.
Otherwise the loop will never end. This will crash your browser. Read
about breaks in a later chapter of this tutorial.
Statement 3
Often statement 3 increases the initial variable.
This is not always the case, JavaScript doesn't care, and statement 3 is
optional.
Statement 3 can do anything like negative increment (i--), positive increment (i
= i + 15), or anything else.
Statement 3 can also be omitted (like when you increment your values inside
the loop):
Example
var i = 0;
i++;
Try it Yourself
Example
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
text += person[x];
Try it yourself
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) {
i++;
Try it yourself
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 {
i++;
Try it yourself
Do not forget to increase the variable used in the condition, otherwise the loop
will never end!
Example
var i = 0;
for (;cars[i];) {
i++;
Try it Yourself
The loop in this example uses a while loop to collect the car names from the
cars array:
Example
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
while (cars[i]) {
i++;
Try it Yourself
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch() statement.
The break statement can also be used to jump out of a loop.
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; }
Try it yourself
Example
if (i === 3) { continue; }
Try it yourself
JavaScript Labels
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 to
skip one loop iteration.
The break statement, without a label reference, can only be used to jump out
of a loop or a switch.
With a label reference, the break statement can be used to jump out of any
code block:
Example
var cars = ["BMW", "Volvo", "Saab", "Ford"];
list: {
break list;
Try it Yourself
string
number
boolean
object
function
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
// Returns object
// Returns object
typeof function () {}
// Returns function
typeof myCar
not declared)
typeof null
// Returns object
Try it Yourself
Please observe:
The
The
The
The
The
data
data
data
data
data
type
type
type
type
type
of
of
of
of
of
NaN is number
an array is object
a date is object
null is object
an undefined variable is undefined
The constructor property returns the constructor function for all JavaScript
variables.
Example
"John".constructor
{ [native code] }
(3.14).constructor
{ [native code] }
false.constructor
{ [native code] }
[1,2,3,4].constructor
{ [native code] }
{name:'John', age:34}.constructor
{ [native code] }
new Date().constructor
{ [native code] }
function () {}.constructor
{ [native code] }
Try it Yourself
You can check the constructor property to find out if an object is an Array
(contains the word "Array"):
Example
function isArray(myArray) {
Try it Yourself
You can check the constructor property to find out if an object is a Date
(contains the word "Date"):
Example
function isDate(myDate) {
Try it Yourself
Example
String(x)
String(123)
String(100 + 23)
expression
Try it Yourself
The Number method toString() does the same.
Example
x.toString()
(123).toString()
(100 + 23).toString()
Try it Yourself
In the chapter Number Methods, you will find more methods that can be used to
convert numbers to strings:
Method
toExponential()
Description
toFixed()
toPrecision()
String(false)
String(true)
// returns "false"
// returns "true"
false.toString()
// returns "false"
true.toString()
// returns "true"
String(Date())
Example
Date().toString()
In the chapter Date Methods, you will find more methods that can be used to
convert dates to strings:
Method
getDate()
Description
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
Number("3.14")
// returns 3.14
Number(" ")
// returns 0
Number("")
// returns 0
Number("99 88")
// returns NaN
In the chapter Number Methods, you will find more methods that can be used to
convert strings to numbers:
Method
Description
parseFloat()
parseInt()
Example
var y = "5";
// y is a string
var x = + y;
// x is a number
Try it Yourself
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)
Try it Yourself
Number(false)
// returns 0
Number(true)
// returns 1
d = new Date();
Number(d)
// returns 1404568027739
d = new Date();
d.getTime()
// returns 1404568027739
5 + null
// returns 5
"5" + null
// returns "5null"
"null"
"5" + 2
// returns 52
"5" - 2
// returns 3
"5" * "2"
// returns 10
to 5 and 2
Try it Yourself
document.getElementById("demo").innerHTML = myVar;
// if myVar = {name:"Fjohn"}
Object]"
// if myVar = [1,2,3,4]
Numbers and booleans are also converted, but this is not very visible:
// if myVar = 123
// if myVar = true
// if myVar = false
Converted
Converted
Converted
Value
to Number
to String
to Boolean
Try it
false
"false"
false
Try it
true
"true"
true
Try it
"0"
false
Try it
"1"
true
Try it
"0"
"0"
true
Try it
"1"
"1"
true
Try it
NaN
NaN
"NaN"
false
Try it
Infinity
Infinity
"Infinity"
true
Try it
-Infinity
-Infinity
"-Infinity"
true
Try it
""
""
false
Try it
"20"
20
"20"
true
Try it
"twenty"
NaN
"twenty"
true
Try it
[]
""
true
Try it
[20]
20
"20"
true
Try it
[10,20]
NaN
"10,20"
true
Try it
["twenty"]
NaN
"twenty"
true
Try it
["ten","twenty"]
NaN
"ten,twenty"
true
Try it
function(){}
NaN
"function(){}"
true
Try it
{}
NaN
"[object Object]"
true
Try it
null
"null"
false
Try it
undefined
NaN
"undefined"
false
Try it
Syntax
/pattern/modifiers;
Example
Example explained:
/w3schools/i is a regular expression.
w3schools is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).
var n = str.search(/w3schools/i);
Try it Yourself
Example
Use a string to do a search for "W3schools" in a string:
var n = str.search("W3Schools");
Try it Yourself
Example
Use a case insensitive regular expression to replace Microsoft with W3Schools in
a string:
var
Visit W3Schools!
Try it Yourself
Try it Yourself
Description
[abc]
Description
[0-9]
(x|y)
Description
\d
Find a digit
\s
\b
\uxxxx
Description
n+
n*
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/;
Since there is an "e" in the string, the output of the code above will be:
true
Try it yourself
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.
It searches a string for a specified pattern, and returns the found text.
If no match is found, it returns null.
The following example searches a string for the character "e":
Example 1
/e/.exec("The best things in life are free!");
Since there is an "e" in the string, the output of the code above will be:
Try it yourself
The reference contains descriptions and examples of all RegExp properties and
methods.
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>
Try it yourself
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 {
catch(err) {
When an error occurs, JavaScript will normally stop, and generate an error
message.
The technical term for this is: JavaScript will raise (or throw) an exception.
// throw a text
throw 500;
// throw a number
If you use throw together with try and catch, you can control program flow
and generate custom error messages.
<!DOCTYPE html>
<html>
<body>
<p id="message"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
x = Number(x);
catch(err) {
</script>
</body>
</html>
Try it yourself
try {
catch(err) {
finally {
Example
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
x = Number(x);
catch(err) {
finally {
document.getElementById("demo").value = "";
Try it yourself
JavaScript Debugging
Previous
Next Chapter
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
debugger.
Built-in debuggers can be turned on and off, forcing errors to be reported to the
user.
With a debugger, you can also set breakpoints (places where code execution can
be stopped), and examine variables while the code is executing.
Normally, otherwise follow the steps at the bottom of this page, you activate
debugging in your browser with the F12 key, and select "Console" in the
debugger menu.
Example
<!DOCTYPE html>
<html>
<body>
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
</body>
</html>
Try it Yourself
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).
Example
var x = 15 * 5;
debugger;
document.getElementbyId("demo").innerHTML = x;
Try it Yourself
Chrome
Firefox Firebug
Internet Explorer
Open the browser.
From the menu, select tools.
From tools, choose developer tools.
Opera
Safari Firebug
JavaScript Hoisting
Previous
Next Chapter
Hoisting is JavaScript's default behavior of moving declarations to the top.
Example 1
x = 5; // Assign 5 to x
elem.innerHTML = x;
// Display x in the
element
var x; // Declare x
Try it yourself
Example 2
var x; // Declare x
x = 5; // Assign 5 to x
elem.innerHTML = x;
// Display x in the
element
Try it yourself
To understand this, you have to understand the term "hoisting".
Hoisting is JavaScript's default behavior of moving all declarations to the top of
the current scope (to the top of the current script or the current function).
Example 1
var x = 5; // Initialize x
var y = 7; // Initialize y
// Display x and y
Try it yourself
Example 2
var x = 5; // Initialize x
var y = 7; // Initialize y
// Display x and y
Try it yourself
Does it make sense that y is undefined in the last example?
This is because only the declaration (var y), not the initialization (=7) is hoisted
to the top.
Because of hoisting, y has been declared before it is used, but because
initializations are not hoisted, the value of y is undefined.
Example 2 is the same as writing:
Example
var x = 5; // Initialize x
var y;
// Declare y
y = 7;
// Assign 7 to y
Try it yourself
// Display x and y
With strict mode, you can not, for example, use undeclared variables.
Strict mode is supported in:
Internet Explorer from version 10. Firefox from version 4.
Chrome from version 13. Safari from version 5.1. Opera from version 12.
Example
"use strict";
x = 3.14;
Try it Yourself
Example
"use strict";
myFunction();
function myFunction() {
y = 3.14;
Try it Yourself
Declared inside a function, it has local scope (only the code inside the function
is in strict mode):
x = 3.14;
myFunction();
function myFunction() {
"use strict";
y = 3.14;
Try it Yourself
"use strict";
x = 3.14;
"use strict";
x = 3.14;
delete x;
"use strict";
"use strict";
"use strict";
var x = 010;
var y = \010;
"use strict";
obj.x = 3.14;
"use strict";
obj.x = 3.14;
"use strict";
"use strict";
"use strict";
"use strict";
For security reasons, eval() is not allowed to create variables in the scope from
which it was called:
"use strict";
alert (x)
In function calls like f(), the this value was the global object. In strict mode, it is
now undefined.
Future reserved keywords are not allowed. These are:
implements
interface
package
private
protected
public
static
field
Watch Out!
The "use strict" directive is only recognized at the beginning of a script
or a function.
Conventions
Previous
Next Chapter
Always use the same coding conventions for all your JavaScript projects.
Variable Names
At W3schools we use camelCase for identifier names (variables and functions).
All names start with a letter.
At the bottom of this page, you will find a wider discussion about naming rules.
firstName = "John";
lastName = "Doe";
price = 19.90;
tax = 0.20;
Examples:
var x = y + z;
Code Indentation
Always use 4 spaces for indentation of code blocks:
Functions:
function toCelsius(fahrenheit) {
Statement Rules
General rules for simple statements:
Always end a simple statement with a semicolon.
Examples:
var values = ["Volvo", "Saab", "Fiat"];
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Functions:
function toCelsius(fahrenheit) {
Loops:
for (i = 0; i < 5; i++) {
x += i;
Conditionals:
if (time < 20) {
} else {
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 its 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"
};
Short objects can be written compressed, on one line, using spaces only
between properties, like this:
Example
document.getElementById("demo").innerHTML =
"Hello Dolly.";
Try it Yourself
Naming Conventions
Always use the same naming convention for all your code. For example:
Variable and function names written as camelCase
Global variable written in UPPERCASE
Constants (like PI) written in UPPERCASE
Should you use hyp-hens, camelCase, or under_scores in variable names?
This is a question programmers often discuss. The answer depends on who you
ask:
Hyphens in HTML and CSS:
HTML5 attributes can start with data- (data-quantity, data-price).
CSS uses hyphens in property-names (font-size).
<script src="myscript.js">
File Extensions
HTML files should have a .html extension (not .htm).
CSS files should have a .css extension.
JavaScript files should have a .js extension.
Performance
Coding conventions are not used by computers. Most rules have little impact on
the execution of programs.
Indentation and extra spaces are not significant in small scripts.
For code in development, readability should be preferred. Larger production
scripts should be minified.
Declarations on Top
It is a good coding practice to put all declarations at the top of each script or
function.
This will:
// Use later
firstName = "John";
lastName = "Doe";
price = 19.90;
discount = 0.10;
var i;
// Use later
Initialize Variables
It is a good coding practice to initialize variables when you declare them.
This will:
Give cleaner code
Provide a single place to initialize variables
Avoid undefined values
lastName = "",
price = 0,
discount = 0,
fullPrice = 0,
myArray = [],
myObject = {};
Example
var x = "John";
Try it Yourself
Or even worse:
Example
var x = new String("John");
Try it Yourself
Use
Use
Use
Use
Example
var x1 = {};
// new object
var x2 = "";
var x3 = 0;
var x4 = false;
var x5 = [];
var
x6 = /()/;
Try it Yourself
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;
Try it yourself
When doing mathematical operations, JavaScript can convert numbers to
strings:
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";
Try it Yourself
Subtracting a string from a string, does not generate an error but returns NaN
(Not a Number):
Example
"Hello" - "Dolly"
// returns NaN
Try it Yourself
Example
0 == "";
// true
1 == "1";
// true
1 == true;
// true
0 === "";
// false
1 === "1";
// false
1 === true;
// false
Try it Yourself
Example
function myFunction(x, y) {
if (y === undefined) {
y = 0;
Try it Yourself
Read more about function parameters and arguments at Function Parameters
Example
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
default:
day = "Unknown";
Try it Yourself
Operator
JavaScript programs may generate unexpected results if a programmer
accidentally uses an assignment operator (=), instead of a comparison operator
(==) in an if statement.
This if statement returns false (as expected) because x is not equal to 10:
var x = 0;
if (x == 10)
Try it Yourself
This if statement returns true (maybe not as expected), because 10 is true:
var x = 0;
if (x = 10)
Try it Yourself
This if statement returns false (maybe not as expected), because 0 is false:
var x = 0;
if (x = 0)
Try it Yourself
var x = 10;
var y = "10";
if (x == y)
Try it Yourself
In strict comparison, data type does matter. This if statement returns false:
var x = 10;
var y = "10";
if (x === y)
Try it Yourself
var x = 10;
switch(x) {
Try it Yourself
This case switch will not display an alert:
var x = 10;
switch(x) {
Try it Yourself
var x = 10 + 5;
// the result in x is 15
var x = 10 + "5";
Try it Yourself
When adding two variables, it can be difficult to anticipate the result:
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;
Try it Yourself
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
if (z == 0.3)
Try it Yourself
To solve the problem above, it helps to multiply and divide:
Example
var z = (x * 10 + y * 10) / 10;
// z will be 0.3
Try it Yourself
Example 1
var x =
"Hello World!";
Try it Yourself
But, breaking a statement in the middle of a string will not work:
Example 2
var x = "Hello
World!";
Try it Yourself
You must use a "backslash" if you must break a statement in a string:
Example 3
var x = "Hello \
World!";
Try it Yourself
Misplacing Semicolon
Because of a misplaced semicolon, this code block will execute regardless of the
value of x:
if (x == 19);
// code block
Try it Yourself
Example 1
function myFunction(a) {
var power = 10
return a * power
Try it Yourself
Example 2
function myFunction(a) {
return a * power;
Try it Yourself
JavaScript will also allow you to break a statement into two lines.
Because of this, example 3 will also return the same result:
Example 3
function myFunction(a) {
var
power = 10;
return a * power;
Try it Yourself
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;
Try it Yourself
The function will return undefined!
Why? Because JavaScript thinks you meant:
Example 5
function myFunction(a) {
var
power = 10;
return;
a * power;
Try it Yourself
Explanation
If a statement is incomplete like:
var
JavaScript will try to complete the statement by reading the next line:
power = 10;
return
return;
Example
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length;
var y = person[0];
Try it Yourself
In JavaScript, objects use named indexes.
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;
var y = person[0];
Try it Yourself
Correct:
points = [40, 100, 1, 5, 25, 10];
Correct:
person = {firstName:"John", lastName:"Doe", age:46}
Incorrect:
if (myObj !== null && typeof myObj !== "undefined")
Correct:
if (typeof myObj !== "undefined" && myObj !== null)
Example
for (var i = 0; i < 10; i++) {
// some code
return i;
Try it Yourself
JavaScript Performance
Previous
Next Chapter
How to speed up your JavaScript code.
Bad Code:
for (i = 0; i < arr.length; i++) {
Better Code:
l = arr.length;
The bad code accesses the length property of an array each time the loop is
iterated.
The better code accesses the length property outside the loop, and makes the
loop run faster.
Example
obj = document.getElementById("demo");
obj.innerHTML = "Hello";
Try it Yourself
document.getElementById("demo").innerHTML = fullName;
With this:
Example
<script>
window.onload = downScripts;
function downScripts() {
element.src = "myScript.js";
document.body.appendChild(element);
</script>
JavaScript Standards
ECMAScript 3 (ES3) was released in December 1999.
ECMAScript 4 (ES4) was abandoned.
ECMAScript 5 (ES5) was released in December 2009.
ECMAScript 6 (ES6) was released in June 2015, and is the latest official version
of JavaScript.
Time passes, and we are now beginning to see complete support for ES5/ES6 in
all modern browsers.
abstract
arguments
boolean
break
byte
case
catch
char
class*
const
continue
debugger
default
delete
do
double
else
enum*
eval
export*
extends*
false
final
finally
float
for
function
goto
if
implements
import*
in
instanceof
int
interface
let
long
native
new
null
package
private
protected
public
return
short
static
super*
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with
yield
Date
eval
function
hasOwnProperty
Infinity
isFinite
isNaN
isPrototypeOf
length
Math
NaN
name
Number
Object
prototype
String
toString
undefined
valueOf
java
JavaArray
javaClass
JavaObject
JavaPackage
all
anchor
anchors
area
assign
blur
button
checkbox
clearInterval
clearTimeou
clientInformation
close
closed
confirm
crypto
decodeU
decodeURIComp
defaultStatus
RI
onent
constructor
document
element
elements
embed
embeds
encodeURI
encodeURIComp
escape
event
fileUpload
onent
focus
form
forms
frame
innerHeight
innerWidth
layer
layers
link
location
mimeTypes
navigate
navigato
frames
frameRate
hidden
history
image
images
offscreenBuff
ering
open
opener
option
outerHeight
outerWidth
packages
pageXOffset
pageYOff
parent
parseFloat
set
parseInt
password
pkcs11
plugin
prompt
propertyIsE
radio
reset
screenX
screenY
scroll
secure
select
self
setInterval
setTimeout
status
submit
taint
text
textarea
top
unescap
untaint
window
num
Examples:
onblur
onclick
onerror
onfocus
onkeydown
onkeypress
onkeyup
onmouseover
onload
onmouseup
onmousedown
onsubmit
JavaScript JSON
Previous
Next Chapter
JSON is a format for storing and transporting data.
JSON is often used when data is sent from a server to a web page.
What is JSON?
JSON
JSON
JSON
JSON
* The JSON syntax is derived from JavaScript object notation syntax, but the
JSON format is text only. Code for reading and generating JSON data can be
written in any programming language.
JSON Example
This JSON syntax defines an employees object: an array of 3 employee records
(objects):
JSON Example
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna",
"lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
"firstName":"John"
JSON Objects
JSON objects are written inside curly braces.
Just like in JavaScript, objects can contain multiple name/value pairs:
{"firstName":"John", "lastName":"Doe"}
JSON Arrays
JSON arrays are written inside square brackets.
Just like in JavaScript, an array can contain objects:
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
In the example above, the object "employees" is an array. It contains three
objects.
Each object is a record of a person (with a first name and a last name).
Then, use the JavaScript built-in function JSON.parse() to convert the string into
a JavaScript object:
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
</script>
Try it Yourself
You can read more about JSON in our JSON tutorial.
JavaScript Forms
Previous
Next Chapter
JavaScript Example
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
return false;
</form>
Try it Yourself
</form>
Try it Yourself
Data Validation
Data validation is the process of ensuring that computer input is clean, correct,
and useful.
Typical validation tasks are:
has the user filled in all required fields?
has the user entered a valid date?
has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct input to a
computer application.
Validation can be defined by many different methods, and deployed in many
different ways.
Server side validation is performed by a web server, after input has been sent
to the server.
Client side validation is performed by a web browser, before input is sent to a
web server.
Description
disabled
max
min
pattern
required
type
:disabled
Description
specified
:invalid
:optional
:required
:valid
Description
checkValidity()
setCustomValidity
()
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
function myFunction() {
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML =
inpObj.validationMessage;
</script>
Try it Yourself
validity
Description
validationMessag
validity is false.
willValidate
Validity Properties
Description
customError
patternMismatch
rangeOverflow
rangeUnderflow
stepMismatch
tooLong
typeMismatch
valueMissing
valid
Examples
If the number in an input field is greater than 100 (the input's max attribute),
display a message:
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
function myFunction() {
if (document.getElementById("id1").validity.rangeOverflow) {
document.getElementById("demo").innerHTML = txt;
</script>
Try it Yourself
If the number in an input field is less than 100 (the input's min attribute),
display a message:
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
function myFunction() {
if (document.getElementById("id1").validity.rangeUnderflow)
{
document.getElementById("demo").innerHTML = txt;
</script>
Try it Yourself
JavaScript Objects
Previous
Next Chapter
JavaScript Objects
In JavaScript, objects are king. If you understand objects, you
understand JavaScript.
In JavaScript, almost "everything" is an object.
Example
var person = "John Doe";
Try it Yourself
Objects are variables too. But objects can contain many values.
The values are written as name : value pairs (name and value separated by a
colon).
Example
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
Try it Yourself
Object Properties
The named values, in JavaScript objects, are called properties.
Property
Value
firstName
John
lastName
Doe
age
50
eyeColor
blue
Object Methods
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
An object method is an object property containing a function definition.
Property
Value
firstName
John
lastName
Doe
age
50
eyeColor
blue
fullName
JavaScript objects are containers for named values, called properties and
methods.
You will learn more about methods in the next chapters.
Example
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
Try it Yourself
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"
};
Try it Yourself
Example
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
Try it Yourself
The two examples above do exactly the same. There is no need to use
new Object().
For simplicity, readability and execution speed, use the first one (the
object literal method).
Example
function person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
Try it yourself
The above function (person) is an object constructor.
Once you have an object constructor, you can create new objects of the same
type:
Example
var x1 = new Object();
var
x6 = new RegExp();
Try it Yourself
The Math() object is not in the list. Math is a global object. The new keyword
cannot be used on Math.
Example
var x1 = {};
// new object
var x2 = "";
var x3 = 0;
var x4 = false;
var x5 = [];
// new array
var
x6 = /()/
var x7 = function(){};
object
Try it Yourself
var x = y;
The object x is not a copy of y. It is y. Both x and y points to the same object.
Any changes to y will also change x, because x and y are the same object.
Example
var x = person;
x.age = 10;
person.age
Try it Yourself
JavaScript Properties
Properties are the values associated with a JavaScript object.
A JavaScript object is a collection of unordered properties.
Properties can usually be changed, added, and deleted, but some are read only.
objectName.property
// person.age
or
objectName["property"]
// person["age"]
or
objectName[expression]
// x = "age"; person[x]
Example 1
person.firstname + " is " + person.age + " years old.";
Try it Yourself
Example 2
person["firstname"] + " is " + person["age"] + " years old.";
Try it Yourself
Syntax
for (variable in object) {
code to be executed
}
The block of code inside of the for...in loop will be executed once for each
property.
Looping through the properties of an object:
Example
var person = {fname:"John", lname:"Doe", age:25};
for (x in person) {
txt += person[x];
Try it yourself
Example
person.nationality = "English";
Try it Yourself
You cannot use reserved words for property (or method) names.
JavaScript naming rules apply.
Deleting Properties
The delete keyword deletes a property from an object:
Example
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
delete person.age;
// or delete person["age"];
Try it Yourself
The delete keyword deletes both the value of the property and the property
itself.
After deletion, the property cannot be used before it is added back again.
The delete operator is designed to be used on object properties. It has no effect
on variables or functions.
The delete operator should not be used on predefined JavaScript object
properties. It can crash your application.
Property Attributes
All properties have a name. In addition they also have a value.
The value is one of the property's attributes.
Other attributes are: enumerable, configurable, and writable.
These attributes define how the property can be accessed (is it readable?, is it
writable?)
In JavaScript, all attributes can be read, but only the value attribute can be
changed (and only if the property is writable).
( ECMAScript 5 has methods for both getting and setting all property attributes)
Prototype Properties
JavaScript objects inherit the properties of their prototype.
The delete keyword does not delete inherited properties, but if you delete a
prototype property, it will affect all objects inherited from the prototype.
Next Chapter
JavaScript Methods
JavaScript methods are the actions that can be performed on objects.
A JavaScript method is a property containing a function definition.
Property
Value
firstName
John
lastName
Doe
age
50
eyeColor
blue
fullName
objectName.methodName()
You will typically describe fullName() as a method of the person object, and
fullName as a property.
The fullName property will execute (as a function) when it is invoked with ().
This example accesses the fullName() method of a person object:
Example
name = person.fullName();
Try it Yourself
If you access the fullName property, without (), it will return the function
definition:
Example
name = person.fullName;
Try it Yourself
This example uses the toUpperCase() method of the String object, to convert a
text to uppercase:
HELLO WORLD!
Example
function person(firstName, lastName, age, eyeColor) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.eyeColor = eyeColor;
this.lastName = name;
The changeName() function assigns the value of name to the person's lastName
property.
Try it Yourself
JavaScript knows which person you are talking about by "substituting" this with
myMother.
JavaScript Prototypes
All JavaScript objects inherit the properties and methods from their prototype.
Objects created using an object literal, or with new Object(), inherit from a
prototype called Object.prototype.
Objects created with new Date() inherit the Date.prototype.
The Object.prototype is on the top of the prototype chain.
All JavaScript objects (Date, Array, RegExp, Function, ....) inherit from the
Object.prototype.
Creating a Prototype
The standard way to create an object prototype is to use an object constructor
function:
Example
function person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
With a constructor function, you can use the new keyword to create new
objects from the same prototype:
Example
var myFather = new person("John", "Doe", 50, "blue");
Try it Yourself
Example
myFather.nationality = "English";
Try it Yourself
The property will be added to myFather. Not to myMother. Not to any other
person objects.
Example
myFather.name = function () {
};
Try it Yourself
The method will be added to myFather. Not to myMother.
You cannot add a new property to a prototype the same way as you add a new
property to an existing object, because the prototype is not an existing object.
Example
person.nationality = "English";
Try it Yourself
To add a new property to a constructor, you must add it to the constructor
function:
Example
function person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English"
Try it Yourself
Example
function person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
Try it Yourself
Example
function person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
person.prototype.nationality = "English";
Try it Yourself
The JavaScript prototype property also allows you to add new methods to an
existing prototype:
Example
function person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
person.prototype.name = function() {
};
Try it Yourself
Function Declarations
Earlier in this tutorial, you learned that functions are declared with the
following syntax:
function functionName(parameters) {
code to be executed
}
Declared functions are not executed immediately. They are "saved for later
use", and will be executed later, when they are invoked (called upon).
Example
function myFunction(a, b) {
return a * b;
Try it yourself
Function Expressions
A JavaScript function can also be defined using an expression.
A function expression can be stored in a variable:
Example
var x = function (a, b) {return a * b};
Try it Yourself
After a function expression has been stored in a variable, the variable can be
used as a function:
Example
var x = function (a, b) {return a * b};
Try it Yourself
The function above is actually an anonymous function (a function without a
name).
Functions stored in variables do not need function names. They are always
invoked (called) using the variable name.
The function above ends with a semicolon because it is a part of an
executable statement.
Example
var myFunction = new Function("a", "b", "return a * b");
Try it Yourself
You actually don't have to use the function constructor. The example above is
the same as writing:
Example
var myFunction = function (a, b) {return a * b};
Try it Yourself
Most of the time, you can avoid using the new keyword in JavaScript.
Function Hoisting
Earlier in this tutorial, you learned about "hoisting".
Hoisting is JavaScript's default behavior of moving declarations to the top of
the current scope.
Hoisting applies to variable declarations and to function declarations.
Because of this, JavaScript functions can be called before they are declared:
myFunction(5);
function myFunction(y) {
return y * y;
}
Functions defined using an expression are not hoisted.
Self-Invoking Functions
Function expressions can be made "self-invoking".
A self-invoking expression is invoked (started) automatically, without being
called.
Function expressions will execute automatically if the expression is followed by
().
You cannot self-invoke a function declaration.
You have to add parentheses around the function to indicate that it is a function
expression:
Example
(function () {
var x = "Hello!!";
})();
Try it Yourself
Example
function myFunction(a, b) {
return a * b;
Try it Yourself
JavaScript functions can be used in expressions:
Example
function myFunction(a, b) {
return a * b;
var x = myFunction(4, 3) * 2;
Try it Yourself
Example
function myFunction(a, b) {
return arguments.length;
Try it Yourself
The toString() method returns the function as a string:
Example
function myFunction(a, b) {
return a * b;
Try it Yourself
code to be executed
Parameter Rules
JavaScript function definitions do not specify data types for parameters.
JavaScript functions do not perform type checking on the passed arguments.
JavaScript functions do not check the number of arguments received.
Parameter Defaults
If a function is called with missing arguments (less than declared), the
missing values are set to: undefined
Example
function myFunction(x, y) {
if (y === undefined) {
y = 0;
Try it Yourself
If a function is called with too many arguments (more than declared), these
arguments cannot be referred, because they don't have a name. They can only
be reached in the arguments object.
Example
x = findMax(1, 123, 500, 115, 44, 88);
function findMax() {
var i;
max = arguments[i];
return max;
Try it Yourself
Or create a function to summarize all input values:
Example
x = sumAll(1, 123, 500, 115, 44, 88);
function sumAll() {
var i, sum = 0;
sum += arguments[i];
return sum;
Try it Yourself
Note that this is not a variable. It is a keyword. You cannot change the
value of this.
return a * b;
myFunction(10, 2);
Try it Yourself
The function above does not belong to any object. But in JavaScript there is
always a default global object.
In HTML the default global object is the HTML page itself, so the function above
"belongs" to the HTML page.
In a browser the page object is the browser window. The function above
automatically becomes a window function.
myFunction() and window.myFunction() is the same function:
Example
function myFunction(a, b) {
return a * b;
window.myFunction(10, 2);
// window.myFunction(10, 2) will
also return 20
Try it Yourself
Example
function myFunction() {
return this;
myFunction();
Try it Yourself
Using the window object as a variable can easily crash your program.
Example
var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
myObject.fullName();
Try it Yourself
The fullName method is a function. The function belongs to the object.
myObject is the owner of the function.
The thing called this, is the object that "owns" the JavaScript code. In this case
the value of this is myObject.
Test it! Change the fullName method to return the value of this:
Example
var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this;
myObject.fullName();
owner object)
Try it Yourself
Example
// This is a function constructor:
this.firstName = arg1;
this.lastName
= arg2;
// This
x.firstName;
Try it Yourself
A constructor invocation creates a new object. The new object inherits the
properties and methods from its constructor.
The this keyword in the constructor does not have a value.
The value of this will be the new object created when the function is
invoked.
Example
function myFunction(a, b) {
return a * b;
// Will return
20
Try it Yourself
Example
function myFunction(a, b) {
return a * b;
Try it Yourself
// Will also
Both methods takes an owner object as the first argument. The only difference
is that call() takes the function arguments separately, and apply() takes the
function arguments in an array.
In JavaScript strict mode, the first argument becomes the value of this in the
invoked function, even if the argument is not an object.
In "non-strict" mode, if the value of the first argument is null or undefined, it is
replaced with the global object.
With call() or apply() you can set the value of this, and invoke a function
as a new method of an existing object.
JavaScript Closures
Previous
Next Chapter
JavaScript variables can belong to the local or global scope.
Private variables can be made possible with closures.
Global Variables
A function can access all variables defined inside the function, like this:
Example
function myFunction() {
var a = 4;
return a * a;
Try it Yourself
But a function can also access variables defined outside the function, like this:
Example
var a = 4;
function myFunction() {
return a * a;
Try it Yourself
In the last example, a is a global variable.
In a web page, global variables belong to the window object.
Global variables can be used (and changed) by all scripts in the page (and in
the window).
In the first example, a is a local variable.
A local variable can only be used inside the function where it is defined. It is
hidden from other functions and other scripting code.
Global and local variables with the same name are different variables. Modifying
one, does not modify the other.
Variables created without the keyword var, are always global, even if
they are created inside a function.
Variable Lifetime
Global variables live as long as your application (your window / your web page)
lives.
Local variables have short lives. They are created when the function is invoked,
and deleted when the function is finished.
A Counter Dilemma
Suppose you want to use a variable for counting something, and you want this
counter to be available to all functions.
You could use a global variable, and a function to increase the counter:
Example
var counter = 0;
function add() {
counter += 1;
add();
add();
add();
Try it Yourself
The counter should only be changed by the add() function.
The problem is, that any script on the page can change the counter, without
calling add().
If I declare the counter inside the function, nobody will be able to change it
without calling add():
Example
function add() {
var counter = 0;
counter += 1;
add();
add();
add();
Try it Yourself
It did not work! Every time I call the add() function, the counter is set to 1.
A JavaScript inner function can solve this.
In this example, the inner function plus() has access to the counter variable in
the parent function:
Example
function add() {
var counter = 0;
plus();
return counter;
Try it Yourself
This could have solved the counter dilemma, if we could reach the plus()
function from the outside.
We also need to find a way to execute counter = 0 only once.
We need a closure.
JavaScript Closures
Remember self-invoking functions? What does this function do?
Example
var add = (function () {
var counter = 0;
})();
add();
add();
add();
Try it Yourself
Example Explained
The variable add is assigned the return value of a self-invoking function.
The self-invoking function only runs once. It sets the counter to zero (0), and
returns a function expression.
This way add becomes a function. The "wonderful" part is that it can access the
counter in the parent scope.
This is called a JavaScript closure. It makes it possible for a function to have
"private" variables.
The counter is protected by the scope of the anonymous function, and can only
be changed using the add function.
A closure is a function having access to the parent scope, even after the
parent function has closed.
With the object model, JavaScript gets all the power it needs to create dynamic
HTML:
JavaScript
JavaScript
JavaScript
JavaScript
JavaScript
JavaScript
JavaScript
can
can
can
can
can
can
can
How
How
How
How
to
to
to
to
The
The
The
The
In other words: The HTML DOM is a standard for how to get, change, add,
or delete HTML elements.
The HTML DOM can be accessed with JavaScript (and with other programming
languages).
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an
HTML element).
A method is an action you can do (like add or deleting 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>
</script>
</body>
</html>
Try it Yourself
In the example above, getElementById is a method, while innerHTML is a
property.
document.getElementById()
Description
document.getElementsByTagName()
document.getElementsByClassName()
Description
element.innerHTML=
element.attribute=
element.setAttribute(attribute,value)
element.style.property=
document.createElement()
Description
document.removeChild()
document.appendChild()
document.replaceChild()
document.write(text)
Description
document.getElementById(id).onclick=fu
nction(){code}
onclick event
Property
Description
DO
M
document.anchors
attribute
document.applets
HTML5)
document.baseURI
document.body
document.cookie
document.doctype
document.documentE
lement
document.documentM
ode
document.documentU
RI
document.domain
server
document.domConfig
document.embeds
document.forms
document.head
document.images
document.implement
document.inputEncodi
ng
set)
document.lastModifie
updated
document.links
ation
a href attribute
document.readyState
document.referrer
document)
document.scripts
document.strictErrorC
document.title
document.URL
hecking
Finding
Finding
Finding
Finding
Finding
HTML
HTML
HTML
HTML
HTML
elements
elements
elements
elements
elements
by
by
by
by
by
id
tag name
class name
CSS selectors
HTML object collections
Example
var myElement = document.getElementById("intro");
Try it Yourself
If the element is found, the method will return the element as an object (in
myElement).
If the element is not found, myElement will contain null.
Example
var x = document.getElementsByTagName("p");
Try it Yourself
This example finds the element with id="main", and then finds all <p>
elements inside "main":
Example
var x = document.getElementById("main");
var y = x.getElementsByTagName("p");
Try it Yourself
Example
var x = document.getElementsByClassName("intro");
Try it Yourself
Finding elements by class name does not work in Internet Explorer 8 and
earlier versions.
Example
var x = document.querySelectorAll("p.intro");
Try it Yourself
Example
var x = document.forms["frm1"];
var i;
document.getElementById("demo").innerHTML = text;
Try it Yourself
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>
Try it yourself
Example
<html>
<body>
<script>
</script>
</body>
</html>
Try it Yourself
This example changes the content of an <h1> element:
Example
<!DOCTYPE html>
<html>
<body>
<script>
</script>
</body>
</html>
Try it Yourself
Example explained:
The HTML document above contains an <h1> element with id="header"
We use the HTML DOM to get the element with id="header"
A JavaScript changes the content (innerHTML) of that element
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>
Try it Yourself
Example explained:
The HTML document above contains an <img> element with id="myImage"
We use the HTML DOM to get the element with id="myImage"
A JavaScript changes the src attribute of that element from "smiley.gif" to
"landscape.jpg"
document.getElementById(id).style.property=new style
The following example changes the style of a <p> element:
Example
<html>
<body>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>
Try it Yourself
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>
Try it Yourself
More Examples
Visibility How to make an element invisible. Do you want to show the element or
not?
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.
To execute code when a user clicks on an element, add JavaScript code to an
HTML event attribute:
onclick=JavaScript
Examples of HTML events:
When
When
When
When
When
When
When
In this example, the content of the <h1> element is changed when a user clicks
on it:
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Try it Yourself
In this example, a function is called from the event handler:
Example
<!DOCTYPE html>
<html>
<body>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
</script>
</body>
</html>
Try it Yourself
Example
Assign an onclick event to a button element:
Try it Yourself
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 = displayDate;
</script>
Try it Yourself
In the example above, a function named displayDate is assigned to an HTML
element with the id="myBtn".
The function will be executed when the button is clicked.
The onload and onunload events are triggered when the user enters or leaves
the page.
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()">
Try it Yourself
Example
<input type="text" id="fname" onchange="upperCase()">
Try it yourself
Try it Yourself
Try it Yourself
More Examples
onmousedown and onmouseup
Change an image when a user holds down the mouse button.
onload
Display an alert box when the page has finished loading.
onfocus
Change the background-color of an input field when it gets focus.
Mouse Events
Change the color of an element when the cursor moves over it.
Exercise 2
Exercise 3
document.getElementById("myBtn").addEventListener("click",
displayDate);
Try it yourself
Syntax
element.addEventListener(event, function, useCapture);
The first parameter is the type of the event (like "click" or "mousedown").
The second parameter is the function we want to call when the event occurs.
The third parameter is a boolean value specifying whether to use event bubbling
or event capturing. This parameter is optional.
Note that you don't use the "on" prefix for the event; use "click" instead
of "onclick".
Try it yourself
You can also refer to an external "named" function:
Example
Alert "Hello World!" when the user clicks on an element:
element.addEventListener("click", myFunction);
function myFunction() {
Try it yourself
Example
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);
Try it yourself
You can add events of different types to the same element:
Example
element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);
Try it yourself
Example
Add an event listener that fires when a user resizes the window:
window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = sometext;
});
Try it yourself
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);
});
Try it yourself
Example
document.getElementById("myP").addEventListener("click",
myFunction, true);
document.getElementById("myDiv").addEventListener("click",
myFunction, true);
Try it yourself
Example
element.removeEventListener("mousemove", myFunction);
Try it yourself
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
1.0
9.0
1.0
1.0
7.0
()
removeEventList
ener()
Note: The addEventListener() and removeEventListener() methods are not
supported in IE 8 and earlier versions and Opera 6.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) {
browsers, except IE 8 and earlier
x.addEventListener("click", myFunction);
} else if (x.attachEvent) {
// For IE 8 and
earlier versions
x.attachEvent("onclick", myFunction);
Try it yourself
DOM Nodes
With the HTML DOM, all nodes in the node tree can be accessed by 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>
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 atext node with the value "DOM Tutorial".
The value of the text node can be accessed by the node's innerHTML property,
or the nodeValue.
In addition to the innerHTML property, you can also use the childNodes and
nodeValue properties to get the content of an element.
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>
Try it Yourself
In the example above, getElementById is a method, while childNodes and
nodeValue are properties.
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.
Using the firstChild property is the same as using childNodes[0]:
Example
<html>
<body>
<script>
myText = document.getElementById("intro").firstChild.nodeValue;
document.getElementById("demo").innerHTML = myText;
</script>
</body>
</html>
Try it Yourself
Example
<html>
<body>
<p>Hello World!</p>
<div>
</div>
<script>
alert(document.body.innerHTML);
</script>
</body>
</html>
Try it Yourself
Example
<html>
<body>
<p>Hello World!</p>
<div>
</div>
<script>
alert(document.documentElement.innerHTML);
</script>
</body>
</html>
Try it Yourself
nodeName
nodeName
nodeName
nodeName
nodeName
is read-only
of an element node is the same as the tag name
of an attribute node is the attribute name
of a text node is always #text
of the document node is always #document
Note: nodeName always contains the uppercase tag name of an HTML element.
NodeType
Element
Attribute
Text
Comment
Document
Next Chapter
Adding and Removing Nodes (HTML Elements)
Example
<div id="div1">
</div>
<script>
para.appendChild(node);
element.appendChild(para);
</script>
Try it Yourself
Example Explained
This code creates a new <p> element:
para.appendChild(node);
Finally you must append the new element to an existing element.
This code finds an existing element:
element.appendChild(para);
Example
<div id="div1">
</div>
<script>
para.appendChild(node);
element.insertBefore(para,child);
</script>
Try it Yourself
Example
<div id="div1">
</div>
<script>
parent.removeChild(child);
</script>
Try it Yourself
Example Explained
This HTML document contains a <div> element with two child nodes (two <p>
elements):
<div id="div1">
parent.removeChild(child);
Example
<div id="div1">
</div>
<script>
para.appendChild(node);
parent.replaceChild(para,child);
</script>
Try it Yourself
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];
Try it Yourself
Note: The index starts at 0.
Example
var
myNodelist = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = myNodelist.length;
Try it Yourself
Example explained:
1. Get all <p> elements in a node list
2. Display the length of the node list
The length property is useful when you want to loop through the nodes in a
node list:
Example
var
myNodelist = document.getElementsByTagName("p");
var i;
for (i = 0; i <
myNodelist.length; i++) {
myNodelist[i].style.backgroundColor = "red";
Try it Yourself
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.
The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.
window.document.getElementById("header");
is the same as:
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).
For Internet Explorer, Chrome, Firefox, Opera, and Safari:
window.innerHeight - the inner height of the browser window
window.innerWidth - the inner width of the browser window
For Internet Explorer 8, 7, 6, 5:
document.documentElement.clientHeight
document.documentElement.clientWidth
or
document.body.clientHeight
document.body.clientWidth
A practical JavaScript solution (covering all browsers):
Example
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
Try it yourself
The example displays the browser window's height and width: (NOT including
toolbars/scrollbars)