Languages
[Edit]
EN

JavaScript - difference between let and var

4 points
Created by:
Dollie-Rutledge
806

In this article, we would like to explain the difference between let and var keywords in JavaScript.

The main differences between let and var keywords

1. Variable hoisting support

The var keyword variables support variable hoisting.

The let keyword variables do not support variable hoisting.

Definition:

Variable hoisting is automatic shifting variable declarations to the top of the source code, making them accessible in the above of the declarations.

 

Example 1 (variable hoisting):

// ONLINE-RUNNER:browser;

a = 1;           // variable hosting allows for assigning before declaration
console.log(a);  // 1

b = 2;           // Uncaught ReferenceError: Cannot access 'b' before initialization
console.log(b);  // NEVER PRINTED!!!

var a;  // a variable declaration
let b;  // b variable declaration

Output:

1
Uncaught ReferenceError: Cannot access 'b' before initialization

 

Example: 2 (variable hoisting):

// ONLINE-RUNNER:browser;

console.log(a);  // undefined
console.log(b);  // Uncaught ReferenceError: Cannot access 'b' before initialization

var a = 1;  // a variable declaration and definition
let b = 2;  // b variable declaration and definition

Output:

undefined
Uncaught ReferenceError: Cannot access 'b' before initialization


Example 3 (normal usage):

// ONLINE-RUNNER:browser;

var a = 1;  // a variable declaration and definition
let b = 2;  // b variable declaration and definition

console.log(a);  // 1
console.log(b);  // 2

Output:

1
2

 

2. The let keyword variables can be created in different scopes:

 let keyword variablesvar keyword variables
global scopeyesyes
function scopeyesyes
curly braces scopeyesno

 

Tips

Use let keyword instead of var to avoiding possible errors related with scopes.

See also

  1. What is scope in JavaScript?

Alternative titles

  1. JavaScript - let vs var
  2. JavaScript - what is the difference between let and var?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join