[Go to site: main page, start]

0% found this document useful (0 votes)
22 views53 pages

Java Script

This JavaScript tutorial provides a comprehensive guide to learning JavaScript, covering everything from basic to advanced concepts. It includes interactive examples, exercises, and quizzes to enhance learning and emphasizes the importance of practice. JavaScript is essential for web development, working alongside HTML and CSS to create dynamic web pages.

Uploaded by

tanzeelahmadyt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views53 pages

Java Script

This JavaScript tutorial provides a comprehensive guide to learning JavaScript, covering everything from basic to advanced concepts. It includes interactive examples, exercises, and quizzes to enhance learning and emphasizes the importance of practice. JavaScript is essential for web development, working alongside HTML and CSS to create dynamic web pages.

Uploaded by

tanzeelahmadyt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaScript Tutorial

Learn JavaScript
JavaScript is the world's most popular programming language.

JavaScript is the programming language of the Web.

JavaScript is easy to learn.

This tutorial will teach you JavaScript from basic to advanced.

Examples in Each Chapter


With our "Try it Yourself" editor, you can edit the source code and view the
result.

Example
My First JavaScript
Click me to display Date and Time

Use the Menu


We recommend reading this tutorial, in the sequence listed in the menu.

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.

This tutorial supplements all explanations with clarifying "Try it Yourself"


examples.
If you try all the examples, you will learn a lot about JavaScript, in a very short
time!

Why Study JavaScript?


JavaScript is one of the 3 languages all web developers must learn:

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages

This tutorial covers every version of JavaScript:

 The Original JavaScript ES1 ES2 ES3 (1997-1999)


 The First Main Revision ES5 (2009)
 The Second Revision ES6 (2015)
 The Yearly Additions (2016, 2017 ... 2021, 2022)

ADVERTISEMENT

Learning Speed
In this tutorial, the learning speed is your choice.

Everything is up to you.

If you are struggling, take a break, or re-read the material.

Always make sure you understand all the "Try-it-Yourself" examples.

The only way to become a clever programmer is to: Practice. Practice. Practice.
Code. Code. Code !

Commonly Asked Questions


 How do I get JavaScript?
 Where can I download JavaScript?
 Is JavaScript Free?

You don't have to get or download JavaScript.

JavaScript is already running in your browser on your computer, on


your tablet, and on your smart-phone.

JavaScript is free to use for everyone.

JavaScript Exercises
Many chapters in this tutorial end with an exercise where you can check your
level of knowledge.

JavaScript Quiz Test


Test your JavaScript skills at W3Schools!

Track Your Progress


Create a free W3Schools account and get access to more features and
learning materials:

 View your completed tutorials, exercises, and quizzes

 Keep an eye on your progress and daily streaks

 Set goals and create learning paths

 Create your own personal website


Note: This is an optional feature. You can study at W3Schools without creating
an account.

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.

It can update and change both HTML and CSS.

It can calculate, manipulate and validate data.

Why Study JavaScript?


JavaScript is one of the 3 languages all web developers must learn:

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages


JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().

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 »

JavaScript Can Change HTML Attribute


Values
In this example JavaScript changes the value of the src (source) attribute of
an <img> tag:

The Light Bulb

Turn on the light Turn off the light

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 »

JavaScript Can Hide HTML Elements


Hiding HTML elements can be done by changing the display style:

Example
[Link]("demo").[Link] = "none";
Try it Yourself »

JavaScript Can Show HTML Elements


Showing hidden HTML elements can also be done by changing
the display style:

Example
[Link]("demo").[Link] = "block";
Try it Yourself »

Did You Know?


JavaScript and Java are completely different languages, both in concept and
design.

JavaScript was invented by Brendan Eich in 1995, and became an ECMA


standard in 1997.

ECMA-262 is the official name 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.

It can update and change both HTML and CSS.

It can calculate, manipulate and validate data.

Why Study JavaScript?


JavaScript is one of the 3 languages all web developers must learn:

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages

JavaScript Can Change HTML Content


One of many JavaScript HTML methods is getElementById().
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 »

JavaScript Can Change HTML Attribute


Values
In this example JavaScript changes the value of the src (source) attribute of
an <img> tag:

The Light Bulb

Turn on the light Turn off the light

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 »

JavaScript Can Hide HTML Elements


Hiding HTML elements can be done by changing the display style:

Example
[Link]("demo").[Link] = "none";
Try it Yourself »

JavaScript Can Show HTML Elements


Showing hidden HTML elements can also be done by changing
the display style:

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.

JavaScript Functions and Events


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> or <body>


You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or
in both.

JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML
page.

The function is invoked (called) when a button is clicked:

Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
[Link]("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h2>Demo JavaScript in Head</h2>

<p id="demo">A Paragraph</p>


<button type="button" 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.

The function is invoked (called) when a button is clicked:

Example
<!DOCTYPE html>
<html>
<body>

<h2>Demo JavaScript in Body</h2>

<p id="demo">A Paragraph</p>

<button type="button" it</button>

<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 file: [Link]


function myFunction() {
[Link]("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="[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.

External scripts cannot contain <script> tags.

External JavaScript Advantages


Placing scripts in external files has some advantages:

 It separates HTML and code


 It makes HTML and JavaScript easier to read and maintain
 Cached JavaScript files can speed up page loads

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:

 With a full URL (a full web address)


 With a file path (like /js/)
 Without any path

This example uses a full URL to link to [Link]:

Example
<script src="[Link]
Try it Yourself »

This example uses a file path to link to [Link]:

Example
<script src="/js/[Link]"></script>

Try it Yourself »

This example uses no path to link to [Link]:

Example
<script src="[Link]"></script>

Try it Yourself »
You can read more about file paths in the chapter HTML File Paths.

JavaScript Output
❮ PreviousNext ❯

JavaScript Display Possibilities


JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML or innerText.


 Writing into the HTML output using [Link]().
 Writing into an alert box, using [Link]().
 Writing into the browser console, using [Link]().

Using innerHTML
To access an HTML element, you can use
the [Link](id) method.

Use the id attribute to identify the HTML element.

Then use the innerHTML property to change the HTML content of the HTML
element:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<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>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<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>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
[Link](5 + 6);
</script>
</body>
</html>

Try it Yourself »

Using [Link]() after an HTML document is loaded, will delete all


existing HTML:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<button type="button" + 6)">Try


it</button>

</body>
</html>

Try it Yourself »

The [Link]() method should only be used for testing.

ADVERTISEMENT

Using [Link]()
You can use an alert box to display data:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>
<script>
[Link](5 + 6);
</script>

</body>
</html>

Try it Yourself »

You can skip the window keyword.

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>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<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.

You will learn more about debugging in a later chapter.

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.

You cannot access output devices from JavaScript.

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>

<button this page</button>

</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.

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
[Link]("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:

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 »

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 White Space


JavaScript ignores multiple spaces. You can add white space to your script to
make it more readable.

The following lines are equivalent:

let person = "Hege";


let person="Hege";

A good practice is to put spaces around operators ( = + - * / ):


let x = y + z;

JavaScript Line Length and Line


Breaks
For best readability, programmers often like to avoid code lines longer than 80
characters.

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 »

JavaScript Code Blocks


JavaScript statements can be grouped together in code blocks, inside curly
brackets {...}.

The purpose of code blocks is to define statements to be executed together.

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.

Our Reserved Words Reference lists all JavaScript keywords.

Here is a list of some of the keywords you will learn about in this tutorial:

Keyword Description

var Declares a variable

let Declares a block variable

const Declares a block constant

if Marks a block of statements to be executed on a condition

switch Marks a block of statements to be executed in different cases

for Marks a block of statements to be executed in a loop

function Declares a function


return Exits a function

try Implements error handling to a block of statements

JavaScript keywords are reserved words. Reserved words cannot be used as


names for variables.

JavaScript syntax is the set of rules, how JavaScript programs are


constructed:

// How to create variables:


var x;
let y;

// How to use variables:


x = 5;
y = 6;
let z = x + y;

JavaScript Values
The JavaScript syntax defines two types of values:

 Fixed values
 Variable values

Fixed values are called Literals.

Variable values are called Variables.

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 »

2. Strings are text, written within double or single quotes:

"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.

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:

let x;
x = 6;

Try it Yourself »

JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10

Try it Yourself »

JavaScript uses an assignment operator ( = ) to assign values to variables:

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.

The computation is called an evaluation.

For example, 5 * 10 evaluates to 50:

5 * 10

Try it Yourself »

Expressions can also contain variable values:

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":

"John" + " " + "Doe"

Try it Yourself »
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.

The let keyword tells the browser to create variables:

let x, y;
x = 5 + 6;
y = x * 10;

Try it Yourself »

The var keyword also tells the browser to create variables:

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".

Code after double slashes // or between /* and */ is treated as a comment.

Comments are ignored, and will not be executed:

let x = 5; // I will be executed

// x = 6; I will NOT be executed

Try it Yourself »

You will learn more about comments in a later chapter.


JavaScript Identifiers / Names
Identifiers are JavaScript names.

Identifiers are used to name variables and keywords, and functions.

The rules for legal names are the same in most programming languages.

A JavaScript name must begin with:

 A letter (A-Z or a-z)


 A dollar sign ($)
 Or an underscore (_)

Subsequent characters may be letters, digits, underscores, or dollar signs.

Note
Numbers are not allowed as the first character in names.

This way JavaScript can easily distinguish identifiers from numbers.

JavaScript is Case Sensitive


All JavaScript identifiers are case sensitive.

The variables lastName and lastname, are two different variables:

let lastname, lastName;


lastName = "Doe";
lastname = "Peterson";

Try it Yourself »

JavaScript does not interpret LET or Let as the keyword let.

JavaScript and Camel Case


Historically, programmers have used different ways of joining multiple words
into one variable name:

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.

Upper Camel Case (Pascal Case):

FirstName, LastName, MasterCard, InterCity.

Lower Camel Case:

JavaScript programmers tend to use camel case that starts with a lowercase
letter:

firstName, lastName, masterCard, interCity.

JavaScript Character Set


JavaScript uses the Unicode character set.

Unicode covers (almost) all the characters, punctuations, and symbols in the
world.

For a closer look, please study our Complete Unicode Reference.

JavaScript Comments
❮ PreviousNext ❯
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


Single line comments start with //.

Any text between // and the end of the line will be ignored by JavaScript (will
not be executed).

This example uses a single-line comment before each code line:

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 */.

Any text between /* and */ will be ignored by JavaScript.


This example uses a multi-line comment (a comment block) to explain the code:

Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
[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.

Using Comments to Prevent Execution


Using comments to prevent execution of code is suitable for code testing.

Adding // in front of a code line changes the code lines from an executable line
to a comment.

This example uses // to prevent execution of one of the code lines:

Example
//[Link]("myH").innerHTML = "My First Page";
[Link]("myP").innerHTML = "My first paragraph.";
Try it Yourself »

This example uses a comment block to prevent execution of multiple lines:

Example
/*
[Link]("myH").innerHTML = "My First Page";
[Link]("myP").innerHTML = "My first paragraph.";
JavaScript Variables
❮ PreviousNext ❯

Variables are Containers for Storing Data


JavaScript Variables can be declared in 4 ways:

 Automatically
 Using var
 Using let
 Using const

In this first example, x, y, and z are undeclared variables.

They are automatically declared when first used:

Example
x = 5;
y = 6;
z = x + y;

Try it Yourself »

Note
It is considered good programming practice to always declare variables before
use.

From the examples you can guess:

 x stores the value 5


 y stores the value 6
 z stores the value 11

Example using var


var x = 5;
var y = 6;
var z = x + y;

Try it Yourself »
Note
The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for older browsers.

Example using let


let x = 5;
let y = 6;
let z = x + y;

Try it Yourself »

Example using const


const x = 5;
const y = 6;
const z = x + y;

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.

These are constant values and cannot be changed.

The variable total is declared with the let keyword.

The value total can be changed.

When to Use var, let, or const?


1. Always declare variables

2. Always use const if the value should not be changed


3. Always use const if the type should not be changed (Arrays and Objects)

4. Only use let if you can't use const

5. Only use var if you MUST support old browsers.

Just Like Algebra


Just like in algebra, variables hold values:

let x = 5;
let y = 6;

Just like in algebra, variables are used in expressions:

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.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits, underscores, and dollar signs.


 Names must begin with a letter.
 Names can also begin with $ and _ (but we will not use it in this tutorial).
 Names are case sensitive (y and Y are different variables).
 Reserved words (like JavaScript keywords) cannot be used as names.

Note
JavaScript identifiers are case-sensitive.

The Assignment Operator


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

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.

(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 Data Types


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
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';

Try it Yourself »

Declaring a JavaScript Variable


Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the var or the let keyword:

var carName;
or:
let carName;

After the declaration, the variable has no value (technically it is 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:

let carName = "Volvo";

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>
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.

One Statement, Many Variables


You can declare many variables in one statement.

Start the statement with let and separate the variables by comma:

Example
let person = "John Doe", carName = "Volvo", price = 200;

Try it Yourself »

A declaration can span multiple lines:

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.

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
let carName;

Try it Yourself »

Re-Declaring JavaScript Variables


If you re-declare a JavaScript variable declared with var, it will not lose its value.

The variable carName will still have the value "Volvo" after the execution of these
statements:

Example
var carName = "Volvo";
var carName;

Try it Yourself »

Note
You cannot re-declare a variable declared with let or const.

This will not work:

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 »
You can also add strings, but strings will be concatenated:

Example
let x = "John" + " " + "Doe";

Try it Yourself »

Also try this:

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 »

JavaScript Dollar Sign $


Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid
variable names:

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".

JavaScript Underscore (_)


Since JavaScript treats underscore as a letter, identifiers containing _ are valid
variable names:

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)

Variables declared with let have Block Scope

Variables declared with let must be Declared before use

Variables declared with let cannot be Redeclared in the same scope

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.

These two keywords provided Block Scope in JavaScript:

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.

You can not accidentally redeclare a variable declared with let.

With let you can not do this:


let x = "John Doe";

let x = 0;

Variables defined with var can be redeclared.

With var you can do this:

var x = "John Doe";

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 »

Difference Between var, let and const

Scope Redeclare Reassign Hoisted Bind

var No Yes Yes Yes Yes

let Yes No Yes No No

const Yes No No No No

What is Good?
let and const have block scope.

let and const can not be redeclared.

let and const must be declared before use.

let and const does not bind to this.

let and const are not hoisted.

What is Not Good?


var does not have to be declared.
var is hoisted.

var binds to this.

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:

Chrome 49 Edge 12 Firefox 36 Safari 11

Mar, 2016 Jul, 2015 Jan, 2015 Sep, 2017

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 »

With let, redeclaring a variable in the same block is NOT allowed:

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
}

Redeclaring a variable with let, in another block, IS 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.

Meaning: You can use the variable before it is declared:

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.

Meaning: Using a let variable before it is declared will result in a ReferenceError:

Example
carName = "Saab";
let carName = "Volvo";

JavaScript Const
❮ PreviousNext ❯

The const keyword was introduced in ES6 (2015)

Variables defined with const cannot be Redeclared

Variables defined with const cannot be Reassigned

Variables defined with const have Block Scope

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;

When to use JavaScript const?


Always declare a variable with const when you know that the value
should not be changed.

Use const when you declare:

 A new Array
 A new Object
 A new Function
 A new RegExp

Constant Objects and Arrays


The keyword const is a little misleading.

It does not define a constant value. It defines a constant reference to a value.

Because of this you can NOT:

 Reassign a constant value


 Reassign a constant array
 Reassign a constant object

But you CAN:

 Change the elements of constant array


 Change the properties of constant object

Constant Arrays
You can change the elements of a constant array:

Example
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];

// You can change an element:


cars[0] = "Toyota";

// You can add an element:


[Link]("Audi");

Try it Yourself »

But you can NOT reassign the array:

Example
const cars = ["Saab", "Volvo", "BMW"];

cars = ["Toyota", "Volvo", "Audi"]; // ERROR

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"};

// You can change a property:


[Link] = "red";

// You can add a property:


[Link] = "Johnson";

Try it Yourself »
But you can NOT reassign the object:

Example
const car = {type:"Fiat", model:"500", color:"white"};

car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR

Try it Yourself »

Difference Between var, let and const

Scope Redeclare Reassign Hoisted Bind

var No Yes Yes Yes Yes

let Yes No Yes No No

const Yes No No No No

What is Good?
let and const have block scope.

let and const can not be redeclared.

let and const must be declared before use.

let and const does not bind to this.

let and const are not hoisted.


What is Not Good?
var does not have to be declared.

var is hoisted.

var binds to this.

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:

Chrome 49 Edge 12 Firefox 36 Safari 11

Mar, 2016 Jul, 2015 Jan, 2015 Sep, 2017

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
}

Reassigning an existing const variable, in the same scope, is 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
}

Redeclaring a variable with const, in another scope, or in another block, is


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.

Meaning: You can use the variable before it is declared:

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.

Meaning: Using a const variable before it is declared will result in


a ReferenceError:

Example
alert (carName);
const carName = "Volvo";

You might also like