JavaScript | Let


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). ES6 or ES2015 defines new keywords to declare varaibles in javascript.

Syntax:

let x=1, y=3, z=4;

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Function Scope:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Block Scope:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Redeclaring Variables in different blocks:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Redeclaring Variables in same blocks:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Does not support Hoisting:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

About immukul

Executive Software Developer at Cavisson Systems