Java Script
Java Script
Learn JavaScript
JavaScript is the world's most popular programming language.
Example
My First JavaScript
Click me to display Date and Time
If you have a large screen, the menu will always be present on the left.
If you have a small screen, open the menu by clicking the top menu sign ☰.
Learn by Examples
Examples are better than 1000 words. Examples are often easier to understand
than text explanations.
ADVERTISEMENT
Learning Speed
In this tutorial, the learning speed is your choice.
Everything is up to you.
The only way to become a clever programmer is to: Practice. Practice. Practice.
Code. Code. Code !
JavaScript Exercises
Many chapters in this tutorial end with an exercise where you can check your
level of knowledge.
JavaScript References
W3Schools maintains a complete JavaScript reference, including all HTML and
browser objects.
The reference contains examples for all properties, methods and events, and is
continuously updated according to the latest web standards.
JavaScript Introduction
❮ PreviousNext ❯
What is JavaScript?
JavaScript is the programming language of the web.
The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":
Example
[Link]("demo").innerHTML = "Hello JavaScript";
Try it Yourself »
JavaScript accepts both double and single quotes:
Example
[Link]('demo').innerHTML = 'Hello JavaScript';
Try it Yourself »
Try it Yourself »
ADVERTISEMENT
Example
[Link]("demo").[Link] = "35px";
Try it Yourself »
Example
[Link]("demo").[Link] = "none";
Try it Yourself »
Example
[Link]("demo").[Link] = "block";
Try it Yourself »
ECMA-262 is the official name of the standard. ECMAScript is the official name of
the language.
JavaScript Introduction
❮ PreviousNext ❯
What is JavaScript?
JavaScript is the programming language of the web.
Example
[Link]("demo").innerHTML = "Hello JavaScript";
Try it Yourself »
JavaScript accepts both double and single quotes:
Example
[Link]('demo').innerHTML = 'Hello JavaScript';
Try it Yourself »
Try it Yourself »
ADVERTISEMENT
JavaScript Can Change HTML Styles
(CSS)
Changing the style of an HTML element, is a variant of changing an HTML
attribute:
Example
[Link]("demo").[Link] = "35px";
Try it Yourself »
Example
[Link]("demo").[Link] = "none";
Try it Yourself »
Example
[Link]("demo").[Link] = "block";
JavaScript Where To
❮ PreviousNext ❯
The <script> Tag
In HTML, JavaScript code is inserted between <script> and </script> tags.
Example
<script>
[Link]("demo").innerHTML = "My First JavaScript";
</script>
Try it Yourself »
Old JavaScript examples may use a type attribute: <script
type="text/javascript">.
The type attribute is not required. JavaScript is the default scripting language in
HTML.
For example, a function can be called when an event occurs, like when the user
clicks a button.
You will learn much more about functions and events in later chapters.
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or
in both.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML
page.
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
[Link]("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
</body>
</html>
Try it Yourself »
ADVERTISEMENT
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML
page.
Example
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
[Link]("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
Try it Yourself »
Placing scripts at the bottom of the <body> element improves the display
speed, because script interpretation slows down the display.
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.
To use an external script, put the name of the script file in the src (source)
attribute of a <script> tag:
Example
<script src="[Link]"></script>
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.
To add several script files to one page - use several script tags:
Example
<script src="[Link]"></script>
<script src="[Link]"></script>
External References
An external script can be referenced in 3 different ways:
Example
<script src="[Link]
Try it Yourself »
Example
<script src="/js/[Link]"></script>
Try it Yourself »
Example
<script src="[Link]"></script>
Try it Yourself »
You can read more about file paths in the chapter HTML File Paths.
JavaScript Output
❮ PreviousNext ❯
Using innerHTML
To access an HTML element, you can use
the [Link](id) method.
Then use the innerHTML property to change the HTML content of the HTML
element:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "<h2>Hello World</h2>";
</script>
</body>
</html>
Try it Yourself »
Note
Changing the innerHTML property of an HTML element is the most common way
to display data in HTML.
Using innerText
To access an HTML element, use the [Link](id) method.
Then use the innerText property to change the inner text of the HTML element:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
[Link]("demo").innerText = "Hello World";
</script>
</body>
</html>
Try it Yourself »
Note
Use innerHTML when you want to change an HTML element.
Use innerText when you only want to change the plain text.
Using [Link]()
For testing purposes, it is convenient to use [Link]():
Example
<!DOCTYPE html>
<html>
<body>
<script>
[Link](5 + 6);
</script>
</body>
</html>
Try it Yourself »
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Try it Yourself »
ADVERTISEMENT
Using [Link]()
You can use an alert box to display data:
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Try it Yourself »
In JavaScript, the window object is the global scope object. This means that
variables, properties, and methods by default belong to the window object. This
also means that specifying the window keyword is optional:
Example
<!DOCTYPE html>
<html>
<body>
<script>
alert(5 + 6);
</script>
</body>
</html>
Try it Yourself »
Using [Link]()
For debugging purposes, you can call the [Link]() method in the browser
to display data.
Example
<!DOCTYPE html>
<html>
<body>
<script>
[Link](5 + 6);
</script>
</body>
</html>
Try it Yourself »
JavaScript Print
JavaScript does not have any print object or print methods.
The only exception is that you can call the [Link]() method in the browser
to print the content of the current window.
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
JavaScript Statements
❮ PreviousNext ❯
Statements
Example
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
Try it Yourself »
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by a computer.
JavaScript Statements
JavaScript statements are composed of:
This statement tells the browser to write "Hello Dolly." inside an HTML element
with id="demo":
Example
[Link]("demo").innerHTML = "Hello Dolly.";
Try it Yourself »
The statements are executed, one by one, in the same order as they are written.
JavaScript programs (and JavaScript statements) are often called JavaScript
code.
Semicolons ;
Semicolons separate JavaScript statements.
Examples
let a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
Try it Yourself »
a = 5; b = 6; c = a + b;
Try it Yourself »
On the web, you might see examples without semicolons.
Ending statements with semicolon is not required, but highly recommended.
If a JavaScript statement does not fit on one line, the best place to break it is
after an operator:
Example
[Link]("demo").innerHTML =
"Hello Dolly!";
Try it Yourself »
One place you will find statements grouped together in blocks, is in JavaScript
functions:
Example
function myFunction() {
[Link]("demo1").innerHTML = "Hello Dolly!";
[Link]("demo2").innerHTML = "How are you?";
}
Try it Yourself »
In this tutorial we use 2 spaces of indentation for code blocks.
You will learn more about functions later in this tutorial.
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript
action to be performed.
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description
JavaScript Values
The JavaScript syntax defines two types of values:
Fixed values
Variable values
JavaScript Literals
The two most important syntax rules for fixed values are:
1. Numbers are written with or without decimals:
10.50
1001
Try it Yourself »
"John Doe"
'John Doe'
Try it Yourself »
ADVERTISEMENT
JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the keywords var, let and const to declare variables.
let x;
x = 6;
Try it Yourself »
JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10
Try it Yourself »
let x, y;
x = 5;
y = 6;
Try it Yourself »
JavaScript Expressions
An expression is a combination of values, variables, and operators, which
computes to a value.
5 * 10
Try it Yourself »
x * 10
Try it Yourself »
Try it Yourself »
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
let x, y;
x = 5 + 6;
y = x * 10;
Try it Yourself »
var x, y;
x = 5 + 6;
y = x * 10;
Try it Yourself »
In these examples, using var or let will produce the same result.
You will learn more about var and let later in this tutorial.
JavaScript Comments
Not all JavaScript statements are "executed".
Try it Yourself »
The rules for legal names are the same in most programming languages.
Note
Numbers are not allowed as the first character in names.
Try it Yourself »
Hyphens:
Hyphens are not allowed in JavaScript. They are reserved for subtractions.
Underscore:
JavaScript programmers tend to use camel case that starts with a lowercase
letter:
Unicode covers (almost) all the characters, punctuations, and symbols in the
world.
JavaScript Comments
❮ PreviousNext ❯
JavaScript comments can be used to explain JavaScript code, and to make it
more readable.
Any text between // and the end of the line will be ignored by JavaScript (will
not be executed).
Example
// Change heading:
[Link]("myH").innerHTML = "My First Page";
// Change paragraph:
[Link]("myP").innerHTML = "My first paragraph.";
Try it Yourself »
This example uses a single line comment at the end of each line to explain the
code:
Example
let x = 5; // Declare x, give it the value of 5
let y = x + 2; // Declare y, give it the value of x + 2
Try it Yourself »
Multi-line Comments
Multi-line comments start with /* and end with */.
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
[Link]("myH").innerHTML = "My First Page";
[Link]("myP").innerHTML = "My first paragraph.";
Try it Yourself »
It is most common to use single line comments.
Block comments are often used for formal documentation.
Adding // in front of a code line changes the code lines from an executable line
to a comment.
Example
//[Link]("myH").innerHTML = "My First Page";
[Link]("myP").innerHTML = "My first paragraph.";
Try it Yourself »
Example
/*
[Link]("myH").innerHTML = "My First Page";
[Link]("myP").innerHTML = "My first paragraph.";
JavaScript Variables
❮ PreviousNext ❯
Automatically
Using var
Using let
Using const
Example
x = 5;
y = 6;
z = x + y;
Try it Yourself »
Note
It is considered good programming practice to always declare variables before
use.
Try it Yourself »
Note
The var keyword was used in all JavaScript code from 1995 to 2015.
The var keyword should only be used in code written for older browsers.
Try it Yourself »
Try it Yourself »
Mixed Example
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
Try it Yourself »
The two variables price1 and price2 are declared with the const keyword.
let x = 5;
let y = 6;
let z = x + y;
From the example above, you can guess that the total is calculated to be 11.
Note
Variables are containers for storing values.
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
Note
JavaScript identifiers are case-sensitive.
This is different from algebra. The following does not make sense in algebra:
x = x + 5
(It calculates the value of x + 5 and puts the result into x. The value of x is
incremented by 5.)
Note
The "equal to" operator is written like == in JavaScript.
JavaScript can handle many types of data, but for now, just think of numbers
and strings.
Strings are written inside double or single quotes. Numbers are written without
quotes.
Try it Yourself »
You declare a JavaScript variable with the var or the let keyword:
var carName;
or:
let carName;
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.
Example
<p id="demo"></p>
<script>
let carName = "Volvo";
[Link]("demo").innerHTML = carName;
</script>
Try it Yourself »
Note
It's a good programming practice to declare all variables at the beginning of a
script.
Start the statement with let and separate the variables by comma:
Example
let person = "John Doe", carName = "Volvo", price = 200;
Try it Yourself »
Example
let person = "John Doe",
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.
The variable carName will have the value undefined after the execution of this
statement:
Example
let carName;
Try it Yourself »
The variable carName will still have the value "Volvo" after the execution of these
statements:
Example
var carName = "Volvo";
var carName;
Try it Yourself »
Note
You cannot re-declare a variable declared with let or const.
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators
like = and +:
Example
let x = 5 + 2 + 3;
Try it Yourself »
You can also add strings, but strings will be concatenated:
Example
let x = "John" + " " + "Doe";
Try it Yourself »
Example
let x = "5" + 2 + 3;
Try it Yourself »
Note
If you put a number in quotes, the rest of the numbers will be treated as strings,
and concatenated.
Example
let x = 2 + 3 + "5";
Try it Yourself »
Example
let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;
Try it Yourself »
Using the dollar sign is not very common in JavaScript, but professional
programmers often use it as an alias for the main function in a JavaScript library.
In the JavaScript library jQuery, for instance, the main function $ is used to
select HTML elements. In jQuery $("p"); means "select all p elements".
Example
let _lastName = "Johnson";
let _x = 2;
let _100 = 5;
Try it Yourself »
Using the underscore is not very common in JavaScript, but a convention among
professional programmers is to use it as an alias for "private (hidden)" variables.
JavaScript Let
❮ PreviousNext ❯
The let keyword was introduced in ES6 (2015)
Block Scope
Before ES6 (2015), JavaScript did not have Block Scope.
JavaScript had Global Scope and Function Scope.
ES6 introduced the two new JavaScript keywords: let and const.
Example
Variables declared inside a { } block cannot be accessed from outside the block:
{
let x = 2;
}
// x can NOT be used here
Global Scope
Variables declared with the var always have Global Scope.
Variables declared with the var keyword can NOT have block scope:
Example
Variables declared with varinside a { } block can be accessed from outside the
block:
{
var x = 2;
}
// x CAN be used here
Cannot be Redeclared
Variables defined with let can not be redeclared.
let x = 0;
var x = 0;
Redeclaring Variables
Redeclaring a variable using the var keyword can impose problems.
Redeclaring a variable inside a block will also redeclare the variable outside the
block:
Example
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
Try it Yourself »
Redeclaring a variable using the let keyword can solve this problem.
Redeclaring a variable inside a block will not redeclare the variable outside the
block:
Example
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Try it Yourself »
const Yes No No No No
What is Good?
let and const have block scope.
Browser Support
The let and const keywords are not supported in Internet Explorer 11 or earlier.
The following table defines the first browser versions with full support:
Redeclaring
Redeclaring a JavaScript variable with var is allowed anywhere in a program:
Example
var x = 2;
// Now x is 2
var x = 3;
// Now x is 3
Try it Yourself »
Example
var x = 2; // Allowed
let x = 3; // Not allowed
{
let x = 2; // Allowed
let x = 3; // Not allowed
}
{
let x = 2; // Allowed
var x = 3; // Not allowed
}
Example
let x = 2; // Allowed
{
let x = 3; // Allowed
}
{
let x = 4; // Allowed
}
Try it Yourself »
Let Hoisting
Variables defined with var are hoisted to the top and can be initialized at any
time.
Example
This is OK:
carName = "Volvo";
var carName;
Try it Yourself »
If you want to learn more about hoisting, study the chapter JavaScript Hoisting.
Variables defined with let are also hoisted to the top of the block, but not
initialized.
Example
carName = "Saab";
let carName = "Volvo";
JavaScript Const
❮ PreviousNext ❯
Cannot be Reassigned
A variable defined with the const keyword cannot be reassigned:
Example
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
Try it Yourself »
Must be Assigned
JavaScript const variables must be assigned a value when they are declared:
Correct
const PI = 3.14159265359;
Incorrect
const PI;
PI = 3.14159265359;
A new Array
A new Object
A new Function
A new RegExp
Constant Arrays
You can change the elements of a constant array:
Example
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];
Try it Yourself »
Example
const cars = ["Saab", "Volvo", "BMW"];
Try it Yourself »
Constant Objects
You can change the properties of a constant object:
Example
// You can create a const object:
const car = {type:"Fiat", model:"500", color:"white"};
Try it Yourself »
But you can NOT reassign the object:
Example
const car = {type:"Fiat", model:"500", color:"white"};
Try it Yourself »
const Yes No No No No
What is Good?
let and const have block scope.
var is hoisted.
Browser Support
The let and const keywords are not supported in Internet Explorer 11 or earlier.
The following table defines the first browser versions with full support:
Block Scope
Declaring a variable with const is similar to let when it comes to Block Scope.
The x declared in the block, in this example, is not the same as the x declared
outside the block:
Example
const x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
Try it Yourself »
You can learn more about block scope in the chapter JavaScript Scope.
Redeclaring
Redeclaring a JavaScript var variable is allowed anywhere in a program:
Example
var x = 2; // Allowed
var x = 3; // Allowed
x = 4; // Allowed
Redeclaring an existing var or let variable to const, in the same scope, is not
allowed:
Example
var x = 2; // Allowed
const x = 2; // Not allowed
{
let x = 2; // Allowed
const x = 2; // Not allowed
}
{
const x = 2; // Allowed
const x = 2; // Not allowed
}
Example
const x = 2; // Allowed
x = 2; // Not allowed
var x = 2; // Not allowed
let x = 2; // Not allowed
const x = 2; // Not allowed
{
const x = 2; // Allowed
x = 2; // Not allowed
var x = 2; // Not allowed
let x = 2; // Not allowed
const x = 2; // Not allowed
}
Example
const x = 2; // Allowed
{
const x = 3; // Allowed
}
{
const x = 4; // Allowed
}
Hoisting
Variables defined with var are hoisted to the top and can be initialized at any
time.
Example
This is OK:
carName = "Volvo";
var carName;
Try it Yourself »
If you want to learn more about hoisting, study the chapter JavaScript Hoisting.
Variables defined with const are also hoisted to the top, but not initialized.
Example
alert (carName);
const carName = "Volvo";