Everything you need to know about var, const, and let.

Raghav Narayan R
Webtips
Published in
4 min readAug 30, 2021

Ever encountered a strange or unexpected behavior while designing your web applications? Or perhaps, are you a beginner to the JavaScript world where you encounter these different variable declarations like var, const, and let without the proper context and usage? Afraid not, let’s decode together the different variable declarations used in JavaScript and what are its effects.

What is Hoisting?

Before we can proceed further with understanding the variable declarations, we need to be aware of an internal mechanism called hoisting. Taking the definition from our MDN docs…,

JavaScript Hoisting refers to the process whereby the compiler allocates memory for variable and function declarations prior to execution of the code. Declarations that are made using var are initialized with a default value of undefined. Declarations made using let and const are not initialized as part of hoisting.

Hoisting simply means making certain types of variables accessible in our code before they are actually declared — “ variables being lifted to the top of their scope”. Concretely, the code will be scanned for variable declarations before execution, and for each variable declaration, a new property gets created to the variable environment object. (window object in global scope)

How does Hoisting work for different variable types?

The way hoisting works for different variable types defines the different types of variable declarations.

Function Declarations: The functions declared using the function declaration do are hoisted to the top of the variable scope. This means that we can use function declarations before they are actually declared in the code and they are scoped to the parent block.

console.log(addNum(2,3)); // Returns 5 function addNum(a,b){
return a + b;
}

Var variables: Variables defined with the var keyword are also hoisted, but hoisted to an initial value of undefined. They are function scoped. This is rather weird behavior, as to why modern JavaScript paved way for let and const variables.

Let and Const variables: Variables defined with the const and let keyword are NOT hoisted and their initial value is set to <uninitialized>. This ensures that these variables cannot be accessed between the beginning of the scope and to the place where it is defined and an error is generated. This behavior saves us from a lot of potential bugs in the future, as it is really bad practice to access variables before they are actually declared.

Example 1:

const myCat = 'James';if (myCat === 'James') {
console.log(`James is a ${type}`); //Reference Error: Cannot access 'type' before initialization
const color = 'Black';
console.log(color);
const type = 'cat';
}

Example 2 :

console.log(gender); // undefined
console.log(age); // Reference Error
console.log(job);
var gender = 'Male';
let age = '50';
const job = 'Developer';

As we see from the above examples, JavaScript throws a reference error when we try to access let or const variables before they are declared.

Function Expressions: We have to remember that functions are first-class based in JavaScript, i.e, they can also be stored and manipulated in the same way as normal variables. Such a function expression behaves in the same way as a normal variable type that was used to define it.

//Functions
console.log(addExpression(5,10)); //Type Error
console.log(addArrow(1,2)); // Type Error

var addExpression = function (a,b){
return a + b;
}
var addArrow = (a,b) => a + b;

In the above example, we are defining the function expressions using the var keyword, so the functions will be hoisted and set to undefined. Calling an undefined function results in a type error.

Pitfalls of var:

Since var variables are function scoped in nature. When we define a var variable outside a function, that variable essentially becomes a property of the global window object. We are polluting the global namespace and making a property available globally. But let and const variables don’t create properties on the window object since they are block-scoped.

var x = 6;
let y = 7;
const z = 10;
console.log(x === window.x ) // Returns true
console.log(y === window.y ) // Returns false
console.log(z === window.z ) // Returns false

If the variable x is used as an important variable for greater operations or processing, since it has become globally exposed, any other function or a variable or a user can accidentally manipulate this var variable and cause unexpected behavior.

var variables can be re-declared and re-assigned.

Let and Const Differences:

  1. Both variable declarations are block-scoped (visibility only within a pair of curly {} braces).
  2. Let can be updated, but cannot be re-assigned like var variable.
  3. Const can neither be updated NOR re-assigned.

Conclusion:

Before initializing a variable, think about how this variable is going to behave in the code. Always try avoiding the usage of var keyword, as it paves way for potential bugs, and use ES6 variable declarations like let and const.

If the variable requires frequent manipulation, use the let keyword. If the variable requires to have a constant value, use the const keyword.

References:

  1. The Complete JavaScript Course 2021 — From Zero To Expert
  2. MDN
  3. Var, Let and Const — What’s the Difference?

--

--