Java Script
Java Script
❮ HomeNext ❯
JavaScript is the programming language of HTML and the Web.
JavaScript is easy to learn.
This tutorial will teach you JavaScript from basic to advanced.
Web pages are not the only place where JavaScript is used. Many desktop and server
programs use JavaScript. Node.js is the best known. Some databases, like MongoDB and
CouchDB, also use JavaScript as their programming language.
JavaScript and Java are completely different languages, both in concept and design.
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in
1997.
ECMA-262 is the official name of the standard. ECMAScript is the official name of the
language.
You can read more about the different JavaScript versions in the chapter JS Versions.
2 JavaScript Introduction
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attribute values.</p>
<p>In this case JavaScript changes the value of the src (source) attribute of an
image.</p>
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on
the light</button>
</body>
</html>
3 JavaScript Where To
The <script> Tag
In HTML, JavaScript code must be inserted between <script> and </script> tags.
Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
A JavaScript function is a block of JavaScript code, that can be executed when "called"
for.
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.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
<!DOCTYPE html>
<html>
<body>
<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
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
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
a <script> tag:
Example
<script src="myScript.js"></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.
External scripts cannot contain <script> tags.
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
External scripts can be referenced with a full URL or with a path relative to the current
web page.
This example uses a full URL to link to a script:
Example
<script src="https://www.w3schools.com/js/myScript1.js"></script>
Try it Yourself »
This example uses a script located in a specified folder on the current web site:
Example
<script src="/js/myScript1.js"></script>
Try it Yourself »
This example links to a script located in the same folder as the current page:
Example
<script src="myScript1.js"></script>
Try it Yourself »
You can read more about file paths in the chapter HTML File Paths.
4 JavaScript Output
JavaScript Display Possibilities
Using innerHTML
<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()
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 »
Using window.alert()
Example
<!DOCTYPE html>
<html>
<body>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Try it Yourself »
Using console.log()
For debugging purposes, you can use the console.log() method to display data.
You will learn more about debugging in a later chapter.
Example
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
5 JavaScript Statements
Example
var x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by a computer.
In a programming language, these programming instructions are called statements.
A JavaScript program is a list of programming statements.
In HTML, JavaScript programs are executed by the web browser.
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";
Try it Yourself »
Most JavaScript programs contain many JavaScript statements.
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.
Add a semicolon at the end of each executable statement:
var 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 »
When separated by semicolons, multiple statements on one line are allowed:
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.
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.
Visit our Reserved Words reference to view a full list of JavaScript keywords.
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging
function
do ... while Executes a block of statements, and repeats the block, while a condition
is true
6 JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed:
var x, y, z; // How to declare variables
x = 5; y = 6; // How to assign values
z = x + y; // How to compute values
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 declare 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 arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10
Try it Yourself »
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
The var keyword tells the browser to create variables:
var x, y;
x = 5 + 6;
y = x * 10;
Try it Yourself »
JavaScript Comments
Not all JavaScript statements are "executed".
Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:
var x = 5; // I will be executed
// var x = 6; I will NOT be executed
Try it Yourself »
You will learn more about comments in a later chapter.
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, or 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.
Hyphens:
first-name, last-name, master-card, inter-city.
Hyphens are not allowed in JavaScript. They are reserved for subtractions.
Underscore:
first_name, last_name, master_card, inter_city.
7 JavaScript Comments
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.
Single Line Comments
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
Multi-line Comments
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 »
Example
Example
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/
8 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 »
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
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
In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.
This is different from algebra. The following does not make sense in algebra:
x=x+5
JavaScript variables can hold numbers like 100 and text values like "John Doe".
In programming, text values are called text strings.
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.
If you put a number in quotes, it will be treated as a text string.
Example
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
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>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
Try it Yourself »
It's a good programming practice to declare all variables at the beginning of a scrip
One Statement, Many Variables
You can declare many variables in one statement.
Start the statement with var and separate the variables by comma:
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
As with algebra, you can do arithmetic with JavaScript variables, using operators
like = and +:
Example
var x = 5 + 2 + 3;
Try it Yourself »
Example
Example
var x = "5" + 2 + 3;
Try it Yourself »
If you put a number in quotes, the rest of the numbers will be treated as strings, and
concatenated.
Now try this:
Example
var x = 2 + 3 + "5";
9 JavaScript Operators
Example
Assignment
var x = 10;
Try it Yourself »
Adding
var x = 5;
var y = 2;
var z = x + y;
Try it Yourself »
Multiplying
var x = 5;
var y = 2;
var z = x * y;
Try it Yourself »
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
Assignment
var x = 10;
x += 5;
Try it Yourself »
Example
John Doe
Try it Yourself »
Example
Adding two numbers, will return the sum, but adding a number and a string will return a
string:
Example
var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;
10
55
Hello5
Try it Yourself »
Operato Description
r
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
Operato Description
r
&& logical and
|| logical or
! logical not
Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an
object type
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
10 JavaScript Arithmetic
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Remainder)
++ Increment
-- Decrement
Arithmetic Operations
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 »
Adding
The addition operator (+) adds numbers:
Example
var x = 5;
var y = 2;
var z = x + y;
Try it Yourself »
Subtracting
Example
var x = 5;
var y = 2;
var z = x - y;
Multiplying
Example
var x = 5;
var y = 2;
var z = x * y;
Dividing
Example
var x = 5;
var y = 2;
var z = x / y;
Try it Yourself »
Remainder
Example
var x = 5;
var y = 2;
var z = x % y;
Incrementing
Example
var x = 5;
x++;
var z = x
Decrementing
Example
var x = 5;
x--;
var z = x;
Exponentiation
The exponentiation operator (**) raises the first operand to the power of the second
operand.
Example
var x = 5;
var z = x ** 2; // result is 25
Example
var x = 5;
var z = Math.pow(x,2); // result is 25
Operator Precedence
Example
var x = 100 + 50 * 3;
Is the result of example above the same as 150 * 3, or is it the same as 100 + 150?
Multiplication (*) and division (/) have higher precedence than addition (+) and
subtraction (-).
And (as in school mathematics) the precedence can be changed by using parentheses:
Example
var x = (100 + 50) * 3;
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;