Everything you should know about var, const, and let

Everything you should know about var, const, and let

I am into JavaScript for more than a year now and this language keeps surprising me even with the topics I thought I already knew. One such is the difference between var, const, and let. After reading the book JavaScript: The Definitive Guide by David Flanagan, I could jot down the difference to three points, and voila! using this I answered many interview questions I gave after reading the book. In this blog, let's explore the three simple points, and upon understanding, you could solve many questions in JavaScript.

  1. Block scope
  2. Redeclaring
  3. Hoisting
  • Block scope

if, for loop, while loop are blocks in JavaScript. var is function scoped whereas const and let are block scoped. That means if we declare any variable using let or const inside an if statement or for loop or while loop, then we cannot access them outside these blocks. If we declare a variable using var inside a block we can access it anywhere in the program since it is function based. That is variables declared using var inside a function cannot be accessed outside the function. This holds true for let and const since they are block-scoped and the function can also be considered to be a block. Let us first explore how the declaration of variables works in a function.

1.PNG

It throws a warning saying usage of undeclared variable. Since the scope of variables starts when they are declared and ends when we close the function. We can return the declared variable value but cannot use the variable itself. Let's see how it works in loops and if statements.

2.PNG

It works similarly in for and while loops. Hence the scope of the variable declared using var extends outside the block but is restricted till a function.

  • Redeclaring

We can redeclare variables using var with the same name but cannot be possible for let and const. We can change the value of the declared variable with both var and let. But we cannot change the value of a variable that is const. Hence var can be redeclared and reassigned, let cannot be redeclared but can be reassigned and const cannot be redeclared and cannot be reassigned.

3.PNG

  • Hoisting

Hoisting is a very important concept in JavaScript and we can see this in variables as well. It simply means lifting up the state to the top of the program even though it is defined somewhere in between the program. In the case of var, let, and const: var is hoisted but let and const are not.

Understanding hoisting in var:

4.PNG

let and const variables can be used only when they are declared.

5.PNG