Var, Let, and Const (with Hoisting) - When to use what?

Var, Let, and Const (with Hoisting) - When to use what?

ยท

5 min read

Introduction

JavaScript offers three keywords for variable declaration: let, var, and const.
Each of these has its use cases.

In this blog post, we'll explore the differences between them and understand when to use each one.

Before reading this Blog I highly recommend you go to the previous blog and read, it so that you will easily get the things that I explain here.

Before seeing when to use what let's see some interesting things related to them -

Hoisting:-

Now let's think what will be the output of this -

check();
console.log(a); 
var a = 10;
function check() {
 console.log("Simplifying JavaScript");
}

Well, I know if you are coming from any other programming language you'll say it will give errors, but you know Javascript is something different.

Here's what we will get after running this -

It should have been an error in many other languages, as it is not possible to access something that is not even created (defined) yet But in JS, We know that in the memory creation phase, it assigns undefined and puts the content of the function to function's memory. And in execution, it then executes whatever is asked. (check the previous blog for a better understanding).

Here, as execution goes line by line and not after compiling, it could only print undefined and nothing else.

This phenomenon is not an error. However, if we remove var a = 10; then it gives an error. Uncaught ReferenceError: x is not defined.

Hoisting is a concept that enables us to extract values of variables and functions even before initializing/assigning value without getting an error and this is happening due to the 1st phase (memory creation phase) of the Execution Context.

So in the previous blog, we learned that execution context gets created in two phases, so even before code execution, memory is created in the case of a variable, it will be initialized as undefined while in the case of a function, the whole function code is placed in the memory.

Some Other Examples -

check(); // Simplifying JavaScript
console.log(y); // Uncaught Reference: y is not defined.
console.log(check); // f check(){ console.log("Namaste JavaScript); }
function check() {
 console.log("Simplifying JavaScript");
}

Here y is not defined in the whole code so it gives an error saying "y is not defined"

Here if we use arrow functions, it sees them as a variable, not a function -

check();
console.log(a);
var a = 10;
var check = () => {
  console.log("Simplifying JavaScript");
};

Undefined vs Not Defined:-

Here lots of places you see word undefined and Not defined Let's see what the difference between them -

In the first phase (memory allocation) JS assigns each variable a placeholder called undefined.

undefined is when memory is allocated for the variable, but no value is assigned yet.

If a variable is not even declared in the memory allocation phase and tried to access then it is Not defined
Not Defined !== Undefined

When a variable is declared but not assigned a value, its current value is undefined. But when the variable itself is not declared but called in code, then it is not defined.

let, var, and const -

var is introduced in ES5 but let and const are introduced in ES6 -

console.log(x); // ReferenceError: Cannot access 'x' before initialization
console.log(y); // prints undefined as expected
let x = 10;
console.log(x); // 10
var y = 15;
console.log(window.x); // undefined
console.log(window.y); // 15

It looks like let isn't hoisted, but it is, let's understand

Both x and y are initialized as undefined in the hoisting stage.

But var y is inside the storage space of GLOBAL, and x is in a separate memory object called script, where it can be accessed only after assigning some value to it first ie. One can access 'x' only if it is assigned. Thus, it throws an error.

In case of var declarations, we can access the data members from the window object (in the case of browsers). But that is not the case for let and const declarations. If we try to do something like this.a or window.a in the global scope relative to the above code, we'll get undefined in return, which we get for anything absent as a key in the window object.

Temporal Dead Zone:-

Time since when the let variable was hoisted until it is initialized some value.

let x = 10;
let x = 100;

In the case of the above code, we'll face the following issue:

So, this means that we're unable to do a re-declaration using let.
Also, in the case of SyntaxErrors, none of the statements of the code are executed.

But if you use var in place of let, it is valid, no error will occur

Now, coming to const. const behaves much more similar than how let behaves, but it is a little stricter than let.

For instance, we can do a let declaration without initialization and initialize the same later. But, we're unable to do the same in case of a const declaration.

const x = 10;
x = 100;

Now, let us come to the difference between these 3 types of errors.

The TypeError which we see in the case of trying to reinitialize a const variable because the variable is of type const and hence it is meant to be a constant.

We face SyntaxErrors whenever we violate the rules of the syntax.

We face ReferenceErrors when the JavaScript Engine tries to find some variable inside the memory space but it's unable to access it.

Now, according to certain conventions followed by the community

  • Always use const it wherever possible. This reduces the possibility of unexpected errors.

  • If not const then we should use let, since due to the presence of the Temporal Dead Zone, we won't face unexpected errors.

  • Keep var aside. But, even if you ever feel the need to use it, use it very consciously. Otherwise, it is an un-preferred method of declaration.

if you want to dive deeply you can check Namaste Javascript by Akshay Saini.

Thanks For Checking this, Happy Coding ๐ŸŽ‰

ย