All about var , let & const in JavaScript.
var , let and const ( VLC ) are the keywords available to us with the help of which we can declare variables in JavaScript. Syntax :
var a = 10;
let b = 20;
const c = 30;
Flow of this article
Declaration
Initialization
Redeclaration
Reinitialization
Scope
Hoisted
Introduced
Revision Sheet
- Declaration : Declaring variables means assigning memory to variables. The scope of this variable depends on where it is declared (function/local or global scope). For example , think variable as a bucket named "a" you bought from some store "X" and its empty now. Not assigned any value.
var a; // allowed
let b; // allowed
const c; // not allowed
SyntaxError: Missing initializer in const declaration
We can declare var and let in one line and initialize later . But with const its not allowed . With const we have to declare a variable and initialize it with value in the same line.
const c = 10 ; // allowed
- Initialization : Initialization means assigning the value in the declared variable .Think it as putting an apple in that bucket that we bought just few minutes ago. Same line Initialization :
var a = 10,
let b = 20;
const c = 30;
Later Initialization : Declaring the variable in one line and initialize it later.
var a;
a = 10; // allowed
let b;
b = 20; // allowed
const c;
c = 30; // not allowed
SyntaxError: Missing initializer in const declaration
- Reinitialization : Giving some value to the same declared variable . It references the same variable in the memory. Assume you are putting another apple at the same place and same bucket. Here we declared var a = 10 once then again we try to reinitialize it. See below comments to understand the example.
var a = 10; //declared once
a = 20; //reintialized again --> its possible with var
let b = 10; //declared once
b = 20; //reintialized again --> its possible with let
const c = 10; //declared once
c = 20; //reintialized again --> its NOT possible with let,
TypeError: Assignment to constant variable.
- Redeclaration : Again declaring same variable name. When we declare variable with the same name then js does not allocates new memory its just update the previous variable with new value. We cannot declare let and const twice in the same scope.
var a = 10;
var a = 20; //its possible to with var
let b = 10;
let b = 20; //its not possible to with let
SyntaxError: Identifier 'b' has already been declared
const c = 10;
const c = 20; //its not possible with const
SyntaxError: Identifier 'c' has already been declared
Think about it : if const variables creates a constant reference to a value then how this modification of complex data works when declared with const keyword. const arr = []; 5. Scope a) Functional Scope : To understand functional scope of var lets see the without keyword variable example first . First lets declare greeting variable WIHTOUT var . When we don't declare variables without any var, let and const , variables gets hoisted globally . To prove what I just said just run below code and you will see that even after the function gets removed from the stack we will still have the greeting reference with us. Otherwise there be error that greeting is not defined.
NOTE:
function wishFoofi() {
greeting = "Hello, foofi!"; // hoisted globally
console.log(greeting);
}
wishFoofi();
console.log(greeting); // Hello, foofi!
Output:
Hello, foofi!
Hello, foofi!
Lets declare greeting variable WITH var now Try this code you will see the error now because when the function gets invoked it will print "Hello, foofi!" in the console.But after the call we all know function will be destroyed from the stack and greeting was functional scoped this time because of var declaration that is not not globally available to us here. So you will see "Hello, foofi!"and an error that greeting is not defined.
function wishFoofi() {
var greeting = "Hello, foofi!"; //greeting remained functional scoped
console.log(greeting);
}
wishFoofi();
console.log(greeting); // error
Output:
Hello, foofi!
ReferenceError: greeting is not defined
With these example we can understand that var is functional scoped. b) Block Scope Anything inside these curly braces {} is block scoped. var : It don't follow block scope as we know its function-scoped , globally-scoped (if declared outside of any function).We can see in below example x is accessible outside the block scope hence its not block scoped. let : It's block scoped. We can see in below example y is not accessible outside the block scope. const : It's also block scoped. We can see in below example z is not accessible outside the block scope.
{
var x = 10;
}
console.log(x); // output 10
{
let y = 20;
}
console.log(y); // output : ReferenceError: y is not defined
{
const z = 30;
}
console.log(z); // output : ReferenceError: z is not defined
- Hoisted var : During compilation phase variables with var are hoisted at the top of the function-scope or globally ( if declared outside of function ) and gets undefined.
console.log(x); // Outputs 'undefined'
var x = 10; // Assignment remains in its original position
Here in this example x is hoisted globally and we get undefined. let and const : variables with let and const are also hoisted but at the top of block scope and they are not assigned with undefined.
console.log(y); // TDZ: ReferenceError:Cannot access 'y' before initialization
. // TDZ: ReferenceError:Cannot access 'y' before initialization
. // TDZ: ReferenceError:Cannot access 'y' before initialization
. // TDZ: ReferenceError:Cannot access 'y' before initialization
. // TDZ: ReferenceError:Cannot access 'y' before initialization
let y = 10; // now initialized so TDZ finished
console.log(y); // 10
In the above example y is hoisted at the top of block but it enters a "temporal dead zone" ( TDZ ) . So we cannot access this variable until the declaration statement is reached. During the TDZ, trying to access the variable results in a ReferenceError. 7. Introduced : var : With var and without any keyword ( x = 10 ) were the only ways to declare variables before the introduction of let and const in ECMAScript 6 (ES6) as known as ECMAScript 2015. Answer of think about it section : Changing reference of a const variable that is not allowed but this restriction is not for the content. So we can change it. a) Changing Content of an array Example
const catsAge = [ 4 , 9 , 10, 8 ];
catsAge[ 4 ] = 13; // this will work perfectly
b) Changing Reference of an array But if you try to assign this array to some another new array then this will give error. Example
const catsAge = [ 4 , 9 , 8 ];
catsAge = [ 2 , 3 , 5 ]; // TypeError: Assignment to constant variable.
Revision Sheet : Quick revision of this article's important points. Revision sheet of var let and const differences.