Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction:
2.
Scope of var
2.1.
Redeclaration and reuse: var
2.2.
var hoisting:
2.3.
Cons with var
3.
Let
3.1.
Hoisting of let
4.
Const
4.1.
Hoisting of const
5.
FAQs
6.
Key takeaways:
Last Updated: Mar 27, 2024

Var, Let and const

Introduction:

We have already covered the lustrous features of ES6 and to date, many of the Javascript developers have already started using it. Many developers have understood and found out the benefits of these features. But our assumption about these usages can be partially true also, as many of the developers can still be in the dark. 

In ES6, one of the interesting features which came out is let and const. To be brief, both are used for variable declaration. We will look into them in more detail in this article below. But the main question is, what makes them differentiate from var, which we are using earlier. Let’s find the answer to this question.Excited Schitts Creek GIF by CBC

 

                                                           Source: Giphy

 

Also See, Javascript hasOwnProperty


Introduction to var

Before the era of ES6, var used to rule the world. But, there were many issues with the usage and declaration of var. Hence, it became necessary to emerge new ways to overcome the flaws. This led to the invention of let and const. But before proceeding ahead, we should be very clear with the concept of var.

 

Scope of var

As the name suggests, scope refers to the boundary or area up to which the variable can be accessed and used. The variables declared under var are global and can be accessed locally too. Var variables can also have function type scope.

Let’s say if any variable is declared outside the function block and can be accessed through the program, then that variable is global. The same work is done by global var type variables. The variables declared with var can be accessed throughout the window.

The scope of var is a function when the variables are declared within any function body. This means they are accessible inside the function body only.

 

var temp = "hey there";
    
    function newFunction() {
        var user = "hello World";
    }

 

Here, temp is globally scoped and is accessible throughout the program. While the user is function scoped because it is declared within the function. Users cannot be accessed outside the function braces. 

 

Redeclaration and reuse: var

The variables declared under var can be reused and redeclared. But the constraint is, this should be done within the same scope.

var temp = "Hey There";
var temp = "Hello Coders";
var temp = "Coding Ninja"

 

Another way,

var temp = "Hey There";
temp = "Hello Coders";
temp = "Coding Ninja"

 

var hoisting:

Hoisting is an interesting feature of javascript. Using hoisting, the variables and functions are moved to the top and are executed at the beginning of code execution. Follow the below example for better clarity:

// If we write this:

console.log (temp);
    var temp = "Coding Ninja"

 

Then it is interpreted as:

var temp;
    console.log(temp); // temp is undefined
    temp = "Coding Ninja"

 

Here, var variables are hoisted to the top of the scope, and the value is initialized with undefined.

 

Cons with var

Take the below example:

var temp = "Hello World";
    var count = 4;

    if (count > 3) {
        var temp = "Hello coders"
    }
    
    console.log(temp) // "Hello Coders"

 

In the example above, as count > 3, the condition is true, and the temp variable is redefined to “Hello coders.” This will not create any problem if we are knowingly changing the variable value. But if there arises a situation when you don’t know that a particular variable is already defined before with the same name and it's getting updated later. For checking you can try it on the online js editor.

Let

To overcome the scenario discussed above, let type variables be used. In other words, it is an improved version of var. But the question is, how can the above problem be solved by let's find it out.

 

Let is block scoped. Block is nothing but a chuck of some code bounded within {}(curly braces). Anything that is written inside these braces, is a block. So, any variable that is defined within a block remains accessible to that block only. Let’s take an example:

let temp = "hello world";
  let count = 4;

  if (count > 3) {
        let arr = "hello coder";
        console.log(arr);// "hello coder".
    }
  console.log(arr) // arr is not defined.

 

 

In the example above, arr is a let variable and it is defined within a block while printing inside the block gives the correct output. But, when it’s printed outside the block, it’s showing the variable is not defined.

 

Like in var, we can redeclare as well as update the variable value. But in let, we can update the value but cannot redeclare it. Any variable declared with let can be updated within its scope. But, the variables cannot be redeclared within the scope. 

let temp = "Hello World";
temp = "Coding Ninja";

 

But, we can redefine the same variable within a different scope. That will work perfectly.

let temp = "Hello World";
    if (true) {
        let temp = "Coding Ninja";
        console.log(temp); // "Coding Ninja"
    }
    console.log(temp); // "Hello World"

 

This code is working fine because, both the instances are treated as different variables and they are having different scopes. 

This advantage of let wins over var. If we are using let, we don’t even need to consider whether we have declared the same variable before or not, as both the instances will be treated in different ways. And another advantage is that any variable can only be declared once within a scope.

Hoisting of let

Like var, let variable declarations are also notched at the top. But, as in var the variables are initialized with undefined, the let variables are not initialized. So, if you try to print the variables before assigning value, you will get a reference error.

Const

As the name suggests, the variables declared as const are constant in nature. Their values are fixed within any scope. Const variables share a few similarities with let. Let’s find out more.

 

Like let declarations, the const variables are block-scoped. That is they can be accessed with the same block they are declared. Const variable values cannot be redeclared or redefined. Once any value is initialized, it cannot be changed. Therefore, at the time of declaration, it should be carefully initialized. The const objects cannot be updated but their properties can be updated as per our requirement.

 

If a code looks:

const temp = {
        arr: "Hello world",
        count: 4
    }

 

Then, we cannot do:

temp = {
        word_: "Hello",
        num: "four"
    } // error:  Assignment to constant variable.

 

But, we can do this:

temp.arr = "say Hello instead";

 

Here, the value of temp. arr is being updated without getting any errors.

Hoisting of const

The const variable also gets notched at the top just like var and let but it is not initialized. 

FAQs

  1. When to use const and when to use let type variables?
    In general, we can declare variables are const, but if the variable value needs to be updated at some point in time, then prefer using let.
     
  2. Can let variables be redeclared?
    No, let variables cannot be redeclared. The variables of let type should be declared before use. The let variables are accessible within a particular block only.
     
  3. Brief the use of var in javascript?
    The variables which are declared as var, the values can be changed later on. In other words, var allows the redeclaration of variables. 
    Syntax: var <variable_name>.
     
  4. Discuss the role of scope in javascript?
    Javascript has both global and local scope. The variables that are declared and initialized outside any function block refer to global variables. And, the variables which are declared and initialized inside any function block refer to local variables.

Key takeaways:

In this article, we started our discussion with var, let, and const with respect to their scope, hoisting. We have also seen what led to the invention of const and let irrespective of let. And at last, we also have covered the differences between them.

Check out Difference Between "var", "let" and "const" in JS here.
 

Keeping the theoretical knowledge at our fingertips helps us get about half the work done. To gain complete understanding, practice is a must. To achieve thorough knowledge, visit our page.

 

Live masterclass