Difference between var, let and const
Dhanusha Perera
Posted on April 12, 2021
Let’s find out what are the differences between var and let in JavaScript.
We can use var or let to declare a variable in JavaScript. Since there are few differences when using these two, we need to have an idea about the difference between using var and let.
var
'var' is used to declare a variable before ES6. Due to its loose behaviour 'let' statement was introduced in ES6 (ECMAScript 2015).
A variable declared with the var has the global scope or function scoped (optionally, initializing it to a value).
Can be accessed using window object.
example 1 - globally scoped
var x = 10;
if (x === 10) {
var x = 20;
console.log(x);
// expected output: 20
}
console.log(x);
// expected output: 20
example 2 - function scoped
var i = 10;
function printAmount(){
var i = 50; // function-scoped variable
console.log(i);
console.log('window object ---> i: ' + window.i); // logs 10
}
console.log(i); // logs 10
printAmount(); // logs 50
let
'let' statement was introduced in ES6 (ECMAScript 2015).
- The scope of a variable declared using let is limited to the block in which it is declared (declares a block-scoped local variable, optionally initializing it to a value).
- Does not get added to the global window object even when it is declared outside any block.
let x = 10;
if (x === 10) {
let x = 20;
console.log(window.x); // no global scope, but block-scoped, thus logs 'undefined'
console.log(x);
// expected output: 20
}
console.log(x);
// expected output: 10
const
Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment, and it can't be redeclared. Introduced in ES6 (ECMAScript 2015).
example
const number = 10;
try {
number = 75;
} catch (err) {
console.log(err);
/* expected output: TypeError: invalid assignment to const `number'.
On Google Chrome: TypeError: Assignment to constant variable.
Note - error messages will vary depending on browser. */
}
console.log(number);
// expected output: 10
Posted on April 12, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
January 1, 2024