JavaScript W3school
JavaScript W3school
Tutorial
❮ HomeNext ❯
JavaScript is the world's most popular programming language.
Example
My First JavaScript
Click me to display Date and Time
Try it Yourself »
<!DOCTYPE html>
<html>
<body>
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>
<p id="demo"></p>
</body>
</html>
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.
If you try all the examples, you will learn a lot about JavaScript, in a very
short time!
JavaScript Examples »
ADVERTISEMENT
Learning Speed
In this tutorial, the learning speed is your choice.
Everything is up to you.
JavaScript is already running in your browser on your computer, on your tablet, and on
your smart-phone.
My Learning
Track your progress with the free "My Learning" program here at W3Schools.
This is an optional feature. You can study W3Schools without using My Learning.
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 ❯
This page contains some examples of what JavaScript can do.
The example below "finds" an HTML element (with id="demo"), and changes the element
content (innerHTML) to "Hello JavaScript":
Example
document.getElementById("demo").innerHTML = "Hello JavaScript";
Try it Yourself »
<!DOCTYPE html>
<html>
<body>
</body>
</html>
JavaScript accepts both double and single quotes:
Example
document.getElementById('demo').innerHTML = 'Hello JavaScript';
Try it Yourself »
<!DOCTYPE html>
<html>
<body>
</body>
</html>
JavaScript Can Change HTML Attribute
Values
In this example JavaScript changes the value of the src (source) attribute of an <img> tag:
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn
on the light</button>
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn
off the light</button>
</body>
</html>
Example
document.getElementById("demo").style.fontSize = "35px";
Try it Yourself »
<!DOCTYPE html>
<html>
<body>
<button type="button"
onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>
</body>
</html>
Example
document.getElementById("demo").style.display = "none";
Try it Yourself »
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<button type="button"
onclick="document.getElementById('demo').style.display='none'">Click Me!</button>
</body>
</html>
Example
document.getElementById("demo").style.display = "block";
Try it Yourself »
<!DOCTYPE html>
<html>
<body>
</body>
</html>
JavaScript Versions »
JavaScript Where To
❮ PreviousNext ❯
Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
Try it Yourself »
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
</script>
</body>
</html>
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.
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() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</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.
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
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="myScript.js"></script>
Try it Yourself »
To add several script files to one page - use several script tags:
Example
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>
External References
An external script can be referenced in 3 different ways:
Example
<script src="https://www.w3schools.com/js/myScript.js"></script>
<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<script src="https://www.w3schools.com/js/myScript.js"></script>
</body>
</html>
Try it Yourself »
Example
<script src="/js/myScript.js"></script>
<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<script src="/js/myScript.js"></script>
</body>
</html>
Try it Yourself »
Example
<script src="myScript.js"></script>
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
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, JavaScript can use
the document.getElementById(id) method.
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Try it Yourself »
Changing the innerHTML property of an HTML element is a common way to
display data in HTML.
Using document.write()
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Try it Yourself »
Using document.write() after an HTML document is loaded, will delete all
existing HTML:
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Try it Yourself »
The document.write() method should only be used for testing.
ADVERTISEMENT
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 »
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 console.log()
For debugging purposes, you can call the console.log() method in the
browser to display data.
Example
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
Try it Yourself »
JavaScript Print
JavaScript does not have any print object or print methods.
Example
<!DOCTYPE html>
<html>
<body>
<button onclick="window.print()">Print this page</button>
</body>
</html>
JavaScript Statements
❮ PreviousNext ❯
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:
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
Try it Yourself »
The statements are executed, one by one, in the same order as they are
written.
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
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p id="demo1"></p>
<script>
let a, b, c;
a = 5;
b = 6;
c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p id="demo"></p>
<script>
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
document.getElementById("demo").innerHTML =
"The value of z is " + z + ".";
</script>
</body>
</html>
Try it Yourself »
a = 5; b = 6; c = a + b;
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello Dolly.";
</script>
</body>
</html>
Try it Yourself »
On the web, you might see examples without semicolons.
Ending statements with semicolon is not required, but highly recommended.
ADVERTISEMENT
let person = "Hege";
let person="Hege";
let x = y + z;
If a JavaScript statement does not fit on one line, the best place to break it is
after an operator:
Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";
Try it Yourself »
Example
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("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 Syntax
❮ PreviousNext ❯
JavaScript syntax is the set of rules, how JavaScript programs are
constructed:
JavaScript Values
The JavaScript syntax defines two types of values:
Fixed values
Variable values
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.
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 »
"John" + " " + "Doe"
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.
JavaScript Comments
Not all JavaScript statements are "executed".
Try it Yourself »
You will learn more about comments in a later chapter.
Note
Numbers are not allowed as the first character in names.
let lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
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.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Numbers</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 10.50;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p id="demo"></p>
<script>
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p id="demo"></p>
<script>
let x;
x = 6;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Operators</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = (5 + 6) * 10;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let x, y;
x = 5;
y = 6;
document.getElementById("demo").innerHTML = x + y;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Expressions</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 * 10;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Expressions</h2>
<p id="demo"></p>
<script>
var x;
x = 5;
document.getElementById("demo").innerHTML = x * 10;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Expressions</h2>
<p id="demo"></p>
<script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let x, y;
x = 5 + 6;
y = x * 10;
document.getElementById("demo").innerHTML = y;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var x, y;
x = 5 + 6;
y = x * 10;
document.getElementById("demo").innerHTML = y;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let x;
x = 5;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript is Case Sensitive</h2>
<p id="demo"></p>
<script>
lastName = "Doe";
lastname = "Peterson";
document.getElementById("demo").innerHTML = lastName;
</script>
</body>
</html>
JavaScript Comments
❮ PreviousNext ❯
Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("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:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("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
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
Try it Yourself »
Example
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/
Try it Yourself »
JavaScript Variables
❮ PreviousNext ❯
Example
var x = 5;
var y = 6;
var z = x + y;
Try it Yourself »
Example
let x = 5;
let y = 6;
let z = x + y;
Try it Yourself »
Example
x = 5;
y = 6;
z = x + y;
Try it Yourself »
If you want your code to run in older browsers, you must use var.
Example
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
Try it Yourself »
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.
ADVERTISEMENT
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
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.
Example
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';
Try it Yourself »
carName = "Volvo";
You can also assign a value to the variable when you declare it:
let carName = "Volvo";
Example
<p id="demo"></p>
<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
Try it Yourself »
Note
It's a good programming practice to declare all variables at the beginning of
a script.
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.
let carName = "Volvo";
let carName;
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 »
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.
Now try this:
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).
Cannot be Redeclared
Variables defined with let can not be redeclared.
let x = 0;
With var you can:
var x = 0;
Block Scope
Before ES6 (2015), JavaScript had Global Scope and Function Scope.
Example
{
let x = 2;
}
// x can NOT be used here
Variables declared inside a { } block can be accessed from outside the block.
Example
{
var x = 2;
}
// x CAN be used here
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 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 »
Browser Support
The let keyword is not fully supported in Internet Explorer 11 or earlier.
The following table defines the first browser versions with full support for
the let keyword:
ADVERTISEMENT
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 »
Variables defined with let are also hoisted to the top of the block, but not
initialized.
Example
carName = "Saab";
let carName = "Volvo";
Try it Yourself »
JavaScript Const
❮ PreviousNext ❯
The const keyword was introduced in ES6 (2015).
Cannot be Reassigned
A const variable 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 Objects and Arrays
The keyword const is a little misleading.
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 »
Example
const car = {type:"Fiat", model:"500", color:"white"};
Try it Yourself »
Browser Support
The const keyword is not fully supported in Internet Explorer.
The following table defines the first browser versions with full support for
the const keyword:
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
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 »
Variables defined with const are also hoisted to the top, but not initialized.
Example
alert (carName);
const carName = "Volvo";
Try it Yourself »
JavaScript Operators
❮ PreviousNext ❯
Assignment Examples
let x = 10;
Try it Yourself »
// Assign the value 5 to x
let x = 5;
// Assign the value 2 to y
let y = 2;
// Assign the value x + y to z:
let z = x + y;
Try it Yourself »
JavaScript Addition
The Addition Operator (+) adds numbers:
Adding
let x = 5;
let y = 2;
let z = x + y;
Try it Yourself »
JavaScript Multiplication
The Multiplication Operator (*) multiplies numbers:
Multiplying
let x = 5;
let y = 2;
let z = x * y;
Try it Yourself »
ADVERTISEMENT
Arithmetic Operators
Assignment Operators
Comparison Operators
String Operators
Logical Operators
Bitwise Operators
Ternary Operators
Type Operators
Try it Yourself »
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
++ Increment
-- Decrement
Assignment
let x = 10;
x += 5;
Try it Yourself »
= 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
**= x **= y x = x ** y
!= not equal
? ternary operator
Example
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
Try it Yourself »
Example
let text1 = "20";
let text2 = "5";
let result = text1 < text2;
Try it Yourself »
Example
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
Try it Yourself »
Example
let text1 = "What a very ";
text1 += "nice day";
Example
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
10
55
Hello5
Try it Yourself »
If you add a number and a string, the result will be a string!
|| logical or
! logical not
Any numeric operand in the operation is converted into a 32 bit number. The
result is converted back to a JavaScript number.
~ NOT ~5 ~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.
~00000000000000000000000000000101 will return
11111111111111111111111111111010
alert(10 5);
JavaScript Arithmetic
❮ PreviousNext ❯
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Remainder)
++ Increment
-- Decrement
Arithmetic Operations
A typical arithmetic operation operates on two numbers.
Example
let x = 100 + 50;
Try it Yourself »
or variables:
Example
let x = a + b;
Try it Yourself »
or expressions:
Example
let x = (100 + 50) * a;
Try it Yourself »
100 + 50
ADVERTISEMENT
Adding
The addition operator (+) adds numbers:
Example
let x = 5;
let y = 2;
let z = x + y;
Try it Yourself »
Subtracting
The subtraction operator (-) subtracts numbers.
Example
let x = 5;
let y = 2;
let z = x - y;
Try it Yourself »
Multiplying
The multiplication operator (*) multiplies numbers.
Example
let x = 5;
let y = 2;
let z = x * y;
Try it Yourself »
Dividing
The division operator (/) divides numbers.
Example
let x = 5;
let y = 2;
let z = x / y;
Try it Yourself »
Remainder
The modulus operator (%) returns the division remainder.
Example
let x = 5;
let y = 2;
let z = x % y;
Try it Yourself »
In arithmetic, the division of two integers produces a quotient and
a remainder.
Incrementing
The increment operator (++) increments numbers.
Example
let x = 5;
x++;
let z = x;
Try it Yourself »
Decrementing
The decrement operator (--) decrements numbers.
Example
let x = 5;
x--;
let z = x;
Try it Yourself »
Exponentiation
The exponentiation operator (**) raises the first operand to the power of
the second operand.
Example
let x = 5;
let z = x ** 2;
Try it Yourself »
Example
let x = 5;
let z = Math.pow(x,2);
Try it Yourself »
Operator Precedence
Operator precedence describes the order in which operations are performed
in an arithmetic expression.
Example
let 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?
Example
let x = (100 + 50) * 3;
Try it Yourself »
When many operations have the same precedence (like addition and
subtraction or multiplication and division), they are computed from left to
right:
Examples
let x = 100 + 50 - 3;
Try it Yourself »
let x = 100 / 50 * 3;
Try it Yourself »
Note
For a full list of operator precedence values go to:
alert(10 2);
JavaScript Assignment
❮ PreviousNext ❯
= 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
**= x **= y x = x ** y
Shift Assignment Operators
Operator Example Same As
^= x ^= y x=x^y
|= x |= y x=x|y
||= x ||= y x = x || (x = y)
??= x ??= y x = x ?? (x = y)
Note
The Logical assignment operators are ES2020.
The = Operator
The Simple Assignment Operator assigns a value to a variable.
Try it Yourself »
let x = 10 + y;
Try it Yourself »
The += Operator
The Addition Assignment Operator adds a value to a variable.
Try it Yourself »
The -= Operator
The Subtraction Assignment Operator subtracts a value from a variable.
Try it Yourself »
The *= Operator
The Multiplication Assignment Operator multiplies a variable.
Try it Yourself »
Try it Yourself »
The /= Operator
The Division Assignment Operator divides a variable.
Try it Yourself »
The %= Operator
The Remainder Assignment Operator assigns a remainder to a variable.
Try it Yourself »
ADVERTISEMENT
Try it Yourself »
The >>= Operator
The Right Shift Assignment Operator right shifts a variable (signed).
Try it Yourself »
Try it Yourself »
Try it Yourself »
The |= Operator
The Bitwise OR Assignment Operator does a bitwise OR operation on two
operands and assigns the result to the variable.
Try it Yourself »
The ^= Operator
The Bitwise XOR Assignment Operator does a bitwise XOR operation on
two operands and assigns the result to the variable.
Try it Yourself »
Try it Yourself »
The &&= operator is an ES2020 feature.
Try it Yourself »
The ||= operator is an ES2020 feature.
Try it Yourself »
The ??= operator is an ES2020 feature.
x = 10;
y = 5;
x y;
JavaScript Data Types
❮ PreviousNext ❯
1. An object
2. An array
3. A date
Examples
// Numbers:
let length = 16;
let weight = 7.5;
// Strings:
let color = "Yellow";
let lastName = "Johnson";
// Booleans
let x = true;
let y = false;
// Object:
const person = {firstName:"John", lastName:"Doe"};
// Array object:
const cars = ["Saab", "Volvo", "BMW"];
// Date object:
const date = new Date("2022-03-25");
Note
A JavaScript variable can hold any type of data.
The Concept of Data Types
In programming, data types is an important concept.
let x = 16 + "Volvo";
Does it make any sense to add "Volvo" to sixteen? Will it produce an error or
will it produce a result?
let x = "16" + "Volvo";
Note
When adding a number and a string, JavaScript will treat the number as a
string.
Example
let x = 16 + "Volvo";
Try it Yourself »
Example
let x = "Volvo" + 16;
Try it Yourself »
JavaScript:
let x = 16 + 4 + "Volvo";
Result:
20Volvo
Try it Yourself »
JavaScript:
let x = "Volvo" + 16 + 4;
Result:
Volvo164
Try it Yourself »
In the second example, since the first operand is a string, all operands are
treated as strings.
ADVERTISEMENT
Example
let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
Try it Yourself »
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
// Using double quotes:
let carName1 = "Volvo XC60";
// Using single quotes:
let carName2 = '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
// Single quote inside double quotes:
let answer1 = "It's alright";
Try it Yourself »
You will learn more about strings later in this tutorial.
JavaScript Numbers
All JavaScript numbers are stored as decimal numbers (floating point).
Example
// With decimals:
let x1 = 34.00;
// Without decimals:
let x2 = 34;
Try it Yourself »
Exponential Notation
Extra large or extra small numbers can be written with scientific
(exponential) notation:
Example
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123
Try it Yourself »
Note
Most programming languages have many number types:
JavaScript BigInt
All JavaScript numbers are stored in a a 64-bit floating-point format.
Example
let x = BigInt("123456789012345678901234567890");
Try it Yourself »
You will learn more about BigInt later in this tutorial.
JavaScript Booleans
Booleans can only have two values: true or false.
Example
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false
Try it Yourself »
JavaScript Arrays
JavaScript arrays are written with square brackets.
Example
const 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.
JavaScript Objects
JavaScript objects are written with curly braces {}.
Try it Yourself »
Example
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"
Try it Yourself »
Example
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"
Try it Yourself »
You will learn more about typeof later in this tutorial.
Undefined
In JavaScript, a variable without a value, has the value undefined. The type
is also undefined.
Example
let car; // Value is undefined, type is undefined
Try it Yourself »
Any variable can be emptied, by setting the value to undefined. The type will
also be undefined.
Example
car = undefined; // Value is undefined, type is undefined
Try it Yourself »
Empty Values
An empty value has nothing to do with undefined.
Example
let car = ""; // The value is "", the typeof is "string"
Try it Yourself »
JavaScript Functions
❮ PreviousNext ❯
Example
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}
Try it Yourself »
Function names can contain letters, digits, underscores, and dollar signs
(same rules as variables).
Function Invocation
The code inside the function will execute when "something" invokes (calls)
the function:
You will learn a lot more about function invocation later in this tutorial.
ADVERTISEMENT
Function Return
When JavaScript reaches a return statement, the function will stop executing.
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; // Function returns the product 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) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
Try it Yourself »
Accessing a function without () will return the function object instead of the
function result.
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;
Try it Yourself »
Functions Used as Variable Values
Functions can be used the same way as you use variables, in all types of
formulas, assignments, and calculations.
Example
Instead of using a variable to store the return value of a function:
let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";
Try it Yourself »
You will learn a lot more about functions later in this tutorial.
Local Variables
Variables declared within a JavaScript function, become LOCAL to the
function.
Example
// code here can NOT use carName
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
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.
function myFunction() {
alert("Hello World!");
}
;
JavaScript Objects
❮ PreviousNext ❯
Object Properties
car.name = Fiat
car.model = 500
car.weight = 850kg
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.
let car = "Fiat";
Try it Yourself »
Objects are variables too. But objects can contain many values.
Try it Yourself »
Object Definition
You define (and create) a JavaScript object with an object literal:
Example
const 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
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Try it Yourself »
Object Properties
The name:values pairs in JavaScript objects are called properties:
firstName John
lastName Doe
age 50
eyeColor blue
objectName.propertyName
or
objectName["propertyName"]
Example1
person.lastName;
Try it Yourself »
Example2
person["lastName"];
Try it Yourself »
JavaScript objects are containers for named values called properties.
Object Methods
Objects can also have methods.
firstName John
lastName Doe
age 50
eyeColor blue
Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
Note
this is not a variable. It is a keyword. You cannot change the value of this.
See Also:
The JavaScript this Tutorial
The this Keyword
In a function definition, this refers to the "owner" of the function.
In the example above, this is the person object that "owns"
the fullName function.
objectName.methodName()
Example
name = person.fullName();
Try it Yourself »
Example
name = person.fullName;
Try it Yourself »
const person = {
firstName: "John",
lastName: "Doe"
};
alert( );
JavaScript Events
❮ PreviousNext ❯
HTML Events
An HTML event can be something the browser does, or something a user
does.
<element event='some JavaScript'>
<element event="some JavaScript">
Example
<button onclick="document.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 »
JavaScript code is often several lines long. It is more common to see event
attributes calling functions:
Example
<button onclick="displayDate()">The time is?</button>
Try it Yourself »
ADVERTISEMENT
Common HTML Events
Here is a list of some common HTML events:
Event Description
onmouseout The user moves the mouse away from an HTML element
Many different methods can be used to let JavaScript work with events:
You will learn a lot more about events and event handlers in the HTML DOM
chapters.