DEV Community

Cover image for Difference between var, let and const
Ubani Friday
Ubani Friday

Posted on • Updated on

Difference between var, let and const

The word var, let and const are keywords for declaring JavaScript variables. Var is an earliest way for declaring variables and still in use by many while let and const is a modern way of declaring variables but there is a difference in using any of them. I will use JavaScript block scope to explain them.

VAR: When a variable is declared using the keyword 'var', it does not follow JavaScript block scope.

Image description

From the code base above, you will observe that the program ran because the keyword "var" does not obey JavaScript block scope. The program was able to compile the global variables which are age = 45, name = 'Malush' and address = '23' despite that the variable 'address' was in a local scope.

LET and CONST: Unlike the 'var' keyword, the 'let' and 'const' obeys JavaScript block scope therefore making the program to fail and throw a ReferenceError of "address is not defined".

Image description

This error just as it were above shows that the variable address declared with the keyword 'let' could not be reached because the variable address was declared within a local scope.

In summary, variable declared with "var" are exposed globally irrespective of its local block, "let" is used to declare a variable which can change at anytime and "const" is used to declare a variable which you don't want to change in the course of that program.

If this was educating please drop a comment and follow me on twitter: https://twitter.com/callmefarad

Top comments (2)

Collapse
 
gbadamson profile image
Gbadamson

This is COOL

Collapse
 
callmefarad profile image
Ubani Friday

Thank you.