1. Overview

In this article, you’ll see different ways to create a variable in EC2015(ES6) in Nodejs. Along with that we will see what is the difference between var, let, and const what is the scope of a particular variable. As we all know scope defines a block of code where we can access the variable. So, let’s get started…

2. Nodejs var with examples

Before the introduction of ES6, we used var to declare any variable whether it is block-scoped or function scopes. In javascript basically var declares function-scoped or global-scoped variable. Meaning either you can access a variable in a function or from anywhere in code.

var a;
function func() {
    var b = 10;
    console.log(a);
    console.log(b);
}
func();
a = 20;
console.log(a);
console.log(b); //ReferenceError: b is not defined

Just think about what it will print before taking a look at the output.

Output :

From the output, you can see that a is undefined because we only declared it, didn’t assign any value. Then it will print the value of b inside a function. It will only print the value of and throw reference error for b. Why this error? It is because of the variable scope. Here, variable a is in global scope while variable b is in function-scope. As we discussed earlier, a globally scoped variable is accessible anywhere in code, and the function scoped variable is accessible inside function block only.

It is working as expected then why we need let and const instead of var. let’s understand it by one example.

var a = 10;
console.log(a);

function func() {
    var b = 20;
    a = 30;
    console.log(b);
    console.log(a);
}
func();
console.log(a);

Output :

Did you get the problem with var? here, function-scoped variable a will overwrite globally-scoped variable a. In this scenario let comes in picture.

3. Nodejs let with examples

let declares block-scoped variable so you can access variable inside the block and its sub-block. Unlike var, let variable is initialized to its value only when parser evaluates it.

let a = 10;
console.log(a);

function func() {
    let b = 20;
    let a = 30;
    console.log(b);
    console.log(a);
}
func();
console.log(a);

Output :

  • Unlike var, let conserves it’s value based on block. Inner block variables don’t overwrite outside block variables. One another difference is the variable declaration. You can declare the same var variable more than once in the block but not the let variable.
function func() {
    var a = 10;
    let b = 20;
    var a = 30;
    // let b = 40; //SyntaxError: Identifier 'b' has already been declared
    console.log(b);
    console.log(a);
}
func();

It will print 20 and 30 and won’t throw any error for variable a re-declaration.

  • Same for the switch-case statements. For the below example it will give an error.
function func(n) {
    switch (n) {
        case 1:
            let a = 10;
            break;
        case 2:
            let a = 20; //Identifier 'a' has already been declared
            break;
    }
}
func(1);

but, if you wrap cases in a block then it will allow you to use let inside it. It will work in a given example and will print both values without any error.

function func(n) {
    switch (n) {
        case 1:
            {
                let a = 10;
                console.log(a);
                break;
            }
        case 2:
            {
                let a = 20;
                console.log(a);
                break;
            }
    }
}
func(1);
  • If you re-declare var variable with let variable inside sub-block it works but vice-versa is not true. It is because of the var variable being hoisted to the top of the block.
var a = 10;
if (a) {
    let a = 20;
    console.log(a); // 20
}
let a = 10;
if (a) {
    var a = 20; // SyntaxError
}

4. Nodejs const with examples

const declares block-scoped variables just like let. The scope can be either local or global. You can not reassign the variable and assignment is a must. You must have to specify values of constant at the time of declaration only. If the variable holds an object you can alter its property.

const a = 10;
if (a) {
    console.log(a); // 10
}
  • const reassignment will throw an error.
const a = 10;
if (a) {
    a = 20; //TypeError: Assignment to constant variable.
}
  • var get hoisted to the top of the block therefore below code will throw a syntax error.
const a = 10;
if (a) {
    var a = 20; //SyntaxError
}
  • let re-declaration will work in sub-blocks only.
const a = 10;
if (a) {
    let a = 20;
    console.log(a); //20
}
  • If you try to override object it will throw an error but if you alter its property and it will work because keys are not protected.
const a = { x: 1, y: 2 };
let b = { z: 3 };
a = b; //TypeError: Assignment to constant variable

a.z = b.z;
console.log(a); //{ x: 1, y: 2, z: 3 }

a.x = b.z;
console.log(a); //{ x: 3, y: 2, z: 3 }
  • You can push into an array but can not reassign new value like object.
const a = [1, 2];
let b = [4];
a = b; //TypeError: Assignment to constant variable

a.push(3);
console.log(a); //[ 1, 2, 3 ]

a.push(b[0]);
console.log(a); //[ 1, 2, 3, 4 ]

5. Conclusion

In this article, we have seen different ways to declare a variable in Nodejs with let, var, and const, the difference between them, and how they are scoped in Nodejs. These concepts are also applicable in basic javascript as these are universal concepts. Hope, you got a clear idea of let, var, and const. Thank you…

6. References

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *