Skip to content
Related Articles

Related Articles

JavaScript | Let

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 25 May, 2022

let is a keyword used to declare variables in JavaScript that are block scoped. There are three ways you can declare variables in JavaScript let, const, var(old). Like other keywords, let keyword could be easily used inside or outside a function as per user requirement. ES6 or ES2015 defines new keywords to declare variables in JavaScript. Generally, it is suggested that we must use the let keyword while working on any major or large-scale project. Even in a small project also, it makes a habit of an individual if let keyword is implemented while variable declaration.
 

Syntax:

Following syntax we may use to declare using let keyword:

let variable_name = value;

 

Block Scope:

A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block. 
 

Global Scope:

 

javascript




let num=10;
console.log(num);
function fun(){
    console.log(num);
}
fun(); // calling the function


Output: 
 

 

Function Scope:

 

javascript




function fun(){
    let num=10;
    console.log(num);
}
fun(); //  calling the function
console.log(num);


Output: 
 

 

Block Scope:

 

javascript




{
    let x=23;
    console.log(x);
}
console.log(x);


Output: 
 

 

Redeclaring Variables in different blocks:

 

javascript




let x=77;
{
    let x=23;
    console.log(x);
}
console.log(x);


Output: 
 

 

Redeclaring Variables in same blocks:

 

javascript




let x=77;
{
    let x=23; // legal
    console.log(x);
}
let x=67;// illegal
console.log(x);


Output: 
 

 

Does not support Hoisting:

 

javascript




x=12;
console.log(x);
let x;


Output: 
 

 Supported Browser:

  • Chrome 49 and above
  • Edge 14 and above
  • Firefox 44 and above
  • Opera 17 and above
  • Internet Explorer 11 and above
  • Safari 10 and above

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!