JavaScript
Introduction
This page contains some examples of what JavaScript can do.
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";
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='[Link]("demo").innerHTML = "Hello
JavaScript!"'>Click Me!</button>
</body>
</html>
JavaScript accepts both double and single quotes:
Example
[Link]('demo').innerHTML = 'Hello JavaScript';
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick=”[Link]("demo").innerHTML =
"[Link]('demo').innerHTML = 'Hello JavaScript!'">Click Me!</button>
</body>
</html>
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
Complete Code:
<!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="[Link]('myImage').src='[Link]
.gif'">Turn on the light</button>
<img id="myImage" src="[Link]
style="width:100px">
<button
onclick="[Link]('myImage').src='[Link]
[Link]'">Turn off the light</button>
</body>
</html>
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";
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button"
onclick="[Link]('demo').[Link]='35px'">Click Me!</button>
</body>
</html>
JavaScript Can Hide HTML Elements
Hiding HTML elements can be done by changing the display style:
Example
[Link]("demo").[Link] = "none";
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button"
onclick="[Link]('demo').[Link]='none'">Click Me!</button>
</body>
</html>
JavaScript Can Show HTML Elements
Showing hidden HTML elements can also be done by changing the display style:
Example
[Link]("demo").[Link] = "block";
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can show hidden HTML elements.</p>
<p id="demo" style="display:none">Hello JavaScript!</p>
<button type="button"
onclick="[Link]('demo').[Link]='block'">Click Me!</button>
</body>
</html>
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 Where To
The <script> Tag
In HTML, JavaScript code is inserted between <script> and </script> tags.
Example
<script>
[Link]("demo").innerHTML = "My First JavaScript";
</script>
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "My First JavaScript";
</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.
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" 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>
<h2>Demo JavaScript in Body</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
[Link]("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
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>
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>Demo External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>This example links to "[Link]".</p>
<p>(myFunction is stored in "[Link]")</p>
<script src="[Link]"></script>
</body>
</html>
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]
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Click Me</button>
<p>This example uses a full web URL to link to "[Link]".</p>
<p>(myFunction is stored in "[Link]")</p>
<script src="[Link]
</body>
</html>
This example uses a file path to link to [Link]:
Example
<script src="/js/[Link]"></script>
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>This example uses a file path to link to "[Link]".</p>
<p>(myFunction is stored in "[Link]")</p>
<script src="/js/[Link]"></script>
</body>
</html>
This example uses no path to link to [Link]:
Example
<script src="[Link]"></script>
JavaScript Output
❮ Previous Next ❯
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
Writing into an HTML element, using innerHTML.
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, JavaScript can use the [Link](id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML
content:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Changing the innerHTML property of an HTML element is a common way to display data in HTML.
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>
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" onclick="[Link](5 + 6)">Try it</button>
</body>
</html>
The [Link]() method should only be used for testing.
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>
You can skip the window keyword.
In JavaScript, the window object is the global scope object, that 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>
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>
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 onclick="[Link]()">Print this page</button>
</body>
</html>
JavaScript Statements
Example
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a
computer.</p>
<p id="demo"></p>
<script>
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
[Link]("demo").innerHTML =
"The value of z is " + z + ".";
</script>
</body>
</html>
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.";
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>In HTML, JavaScript statements are executed by the browser.</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello Dolly.";
</script>
</body>
</html>
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
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>JavaScript statements are separated by semicolons.</p>
<p id="demo1"></p>
<script>
let a, b, c;
a = 5;
b = 6;
c = a + b;
[Link]("demo1").innerHTML = c;
</script>
</body>
</html>
When separated by semicolons, multiple statements on one line are allowed:
a = 5; b = 6; c = a + b;
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>Multiple statements on one line are allowed.</p>
<p id="demo1"></p>
<script>
let a, b, c;
a = 5; b = 6; c = a + b;
[Link]("demo1").innerHTML = c;
</script>
</body>
</html>
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!";
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>
The best place to break a code line is after an operator or a comma.
</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML =
"Hello Dolly!";
</script>
</body>
</html>
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?";
}
Complete Code:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>JavaScript code blocks are written between { and }</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
function myFunction() {
[Link]("demo1").innerHTML = "Hello Dolly!";
[Link]("demo2").innerHTML = "How are you?";
}
</script>
</body>
</html>
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
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
2. Strings are text, written within double or single quotes:
"John Doe"
'John Doe'
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;
JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10
JavaScript uses an assignment operator ( = ) to assign values to variables:
let x, y;
x = 5;
y = 6;
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
Expressions can also contain variable values:
x * 10
The values can be of various types, such as numbers and strings.
For example, "John" + " " + "Doe", evaluates to "John Doe":
"John" + " " + "Doe"
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;
The var keyword also tells the browser to create variables:
var x, y;
x = 5 + 6;
y = x * 10;
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
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.
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";
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
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.";
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
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.";
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.";
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
There are 3 ways to declare a JavaScript variable:
Using var
Using let
Using const
This chapter uses var.
The let and const keywords are explained in the next chapters.
Variables
Variables are containers for storing data (values).
In this example, x, y, and z, are variables, declared with the var keyword:
Example
var x = 5;
var y = 6;
var z = x + y;
From the example above, you can expect:
x stores the value 5
y stores the value 6
z stores the value 11
Much Like Algebra
In this example, price1, price2, and total, are variables:
Example
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
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
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
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.)
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
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
Declaring (Creating) JavaScript Variables
Creating a variable in JavaScript is called "declaring" a variable.
You declare a JavaScript variable with the var keyword:
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:
var 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>
var carName = "Volvo";
[Link]("demo").innerHTML = carName;
</script>
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 var and separate the variables by comma:
var person = "John Doe", carName = "Volvo", price = 200;
A declaration can span multiple lines:
var person = "John Doe",
carName = "Volvo",
price = 200;
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;
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable, 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;
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators
like = and +:
Example
var x = 5 + 2 + 3;
You can also add strings, but strings will be concatenated:
Example
var x = "John" + " " + "Doe";
Also try this:
Example
var x = "5" + 2 + 3;
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";
JavaScript Dollar Sign $
Remember that JavaScript identifiers (names) must begin with:
A letter (A-Z or a-z)
A dollar sign ($)
Or an underscore (_)
Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable
names:
Example
var $$$ = "Hello World";
var $ = 2;
var $myMoney = 5;
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
var _lastName = "Johnson";
var _x = 2;
var _100 = 5;
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
The let keyword was introduced in ES6 (2015).
Variables defined with let cannot be Redeclared.
Variables defined with let must be Declared before use.
Variables defined with let have Block Scope.
Cannot be Redeclared
Variables defined with let cannot be redeclared.
You cannot accidentally redeclare a variable.
With let you can not do this:
Example
let x = "John Doe";
let x = 0;
// SyntaxError: 'x' has already been declared
With var you can:
Example
var x = "John Doe";
var x = 0;
Block Scope
Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
ES6 introduced two important new JavaScript keywords: let and const.
These two keywords provide Block Scope in JavaScript.
Variables declared inside a { } block cannot be accessed from outside the block:
Example
{
let x = 2;
}
// x can NOT be used here
Variables declared with the var keyword can NOT have block scope.
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
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
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:
Chrome 49 Edge 12 Firefox 44 Safari 11 Opera 36
Mar, 2016 Jul, 2015 Jan, 2015 Sep, 2017 Mar, 2016
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
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
}
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;
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
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 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
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?
As a general rule, always declare a variable with const unless you know that the value will change.
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");
But you can NOT reassign the array:
Example
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"]; // ERROR
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";
But you can NOT reassign the object:
Example
const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR
Browser Support
The const keyword is not supported in Internet Explorer 10 or earlier.
The following table defines the first browser versions with full support for
the const keyword:
Chrome 49 IE 11 / Edge Firefox 36 Safari 10 Opera 36
Mar, 2016 Oct, 2013 Feb, 2015 Sep, 2016 Mar, 2016
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
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
}
Const 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;
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";