Table of Contents
Back Button
Back to Chapter
Control Statements
No items found.
Function & Events
No items found.
Array and its Types
No items found.
OOP : Object Oriented Programming
No items found.
Javascript Standards
No items found.
HTML DOM
No items found.
Javascript : Advanced 1
No items found.
Javascript : Advanced 2
No items found.
Additional JavaScript
No items found.

JavaScript Let & Const

Introduction

When the New Updation Came in Javascript in 2015, That Was ES2015 or ES6. It introduced Two New Important Keywords: let and const

Both These keywords have very unique feature of providing  Block Scope  Variables and Constants.

Before ES6, JavaScript had only two types of scope:  Global Scope  and  Function Scope.  (We will be discussing them in Javascript Functions Chapter).

Let is used for declaring variable same like var but it has Block Scope.

const is used to declare a constant.

Block Scope

Let's understand what is meant by Block?

Block is a Group of Code in Javascript and is represented by { }

Scope means reach of object (let) to other parts (blocks) of the code.

Example :

Here, We are discussing a variable that is declared using let and const , so let can be only accessible in the block it is declared i.e inside the { } Brackets.

Var can be accessible in the block and as well as outside the block in which it is declared.

About Let

Let vs Var

Declaring var , it does not have Block Scope.

{
 var x = 2;
}
// x CAN be used here

Here,

x can be accessed both outside and inside a Block.

Declaring let , it have Block Scope.

{
 let x = 2;
}
// x can NOT be used here

Here,

x cannot be accessed outside of the Block, it can only be accessed inside a Block.

About Constant

Declaring const in Javascript

Declaring a variable with const is similar to let when it comes to Block Scope.

var x = 10;
// Here x is 10
{
 const x = 2;
 // Here x is 2
}
// Here x is 10

Here,

The x declared in the block is not the same as the x declared outside the block.

Properties of constant

Javascript Constant have the same value that they are assigned throughout the Scope.

When we try to do any change in value of a constant the program will give an error.

Example :

const PI = 3.141592653589793;
PI = 3.14;      // This will give an error
PI = PI + 10;   // This will also give an error

Note :

You can only assign the value of the const when they are declared.

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?