Difference between var, let and const in Javascript

In javascript in order to create a variable we use 'var' keyword. But in ES6 they have introduced two more ways to create a variable. They are 'let' and 'const' keyword.

The 'var' and 'let' keywords are used to create a variable whose value can be changed at any point of time in the program but 'const' keyword allows us to create a variable whose value cannot be changed.


TypeError: Assignment to constant variable.

In the above program we have created 3 variables. Variable 'x' is declared with var keyword and assigned a value of 10. In the next line we change the value of 'x' to 5 and console the value of the variable 'x' which will print 5. Similarly we declare a variable 'y' and assign a value 10 and in the next line we change it to 5 and console the value of variable 'y' which will print 5.

Next we declare variable 'z' and assign value 10. Then in the next line when trying to change the value of z to 5 it would throw an error stating

'TypeError: Assignment to constant variable.'.

This is because constant variable once assigned a value cannot be changed later in the program.

Variable declared using const keyword should be assigned a value during its declaration itself. If a const variable is declared and if value is not assigned to it then it would throw an error.



const z;
SyntaxError: Missing initializer in const declaration

Now its important to know the difference between var and let keywords. 'const' and 'let' keywords has block scope but 'var' keywords has function scope.



In the above code we declared a function checkEligible which get role as parameter. If the role is 'admin' then we declare a variable 'isEligible' and assign it to true. Then we console 'isEligible' variable. In the code, even though we declare a variable inside if block we can access the variable all through the function. This is because a variable declared with 'var' keyword can be used anywhere inside the function.

Now lets rewrite the above code with let keyword

This will throw an error ' ReferenceError: isEligible is not defined'. This is because 'let' keyword is block scoped. So it can be used within the if block alone. Its scope is not extended everywhere inside the function.

Most Read