JavaScript for LWC: Variables (var, let and const)

What is Variable?

Variables are used to store the data. JavaScript is a dynamically typed language hence, type of variable decided at runtime. We can declare variables is JavaScript by three ways using var, let and const keyword. In ES6 let and const was introduced.

Function and Block scope variables

In JS scope means accessibility and visibility of variables within different part of code. Variables declare inside a function using var keyword are function scoped. This means variable exist only within function in which it is declared or nearest parent function in case of nested function. Block scope introduced in ES6 with let and const keyword. It means that variables are only accessible within a block in which they are defined. Block defined by {} curly braces.

Function scope variables using var keyword

var x = 5;
function functionScopeEx(){
    var x = 10;
    if(true){
        console.log(x); //prints 10
        var y = 20;
    }
    console.log(y); //prints 20 illustrates function scope
}
functionScopeEx();
console.log(x); //prints 5 from line 1 as scope of line 3 x is from line 2 to line 9
console.log(y); //Error: ReferenceError y is not defined scope of variable y is out of scope.
10
20
5
ReferenceError: y is not defined

In the above example variable y declared inside if block still it is visible and accessible outside if block. As, declaration of y done using var keyword which is function scope hence, it throws error when we try to access y outside the function.

Block scope variables using let keyword

function blockScopeEx(){
    let x = 10;
    if(true){
        console.log(x); //prints 10 from line 4
        let y = 20;
    }
    console.log(y); //ReferenceError: y is not defined
}

blockScopeEx();
10
ReferenceError: y is not defined

In the above example, declaration of y done inside if block using let keyword hence, it is not accessible outside if block though we try to access it in same function. It is showing block scope feature similar to other programming languages like C++, C# etc.

What is a need of let?

As we know var supports function scope. It causes a lot of headache to JavaScript developers especially when variable declared in for loops.

Variables uses var keyword for declaration hoisted at top of their scope which leads to confusion or unexpected behavior. But, attempting to access let variable before declaration gives ReferenceError.

function hoistingEx(){
    console.log(x);
    var x = 10;
    console.log(x);
}

hoistingEx();
undefined
10

In the above example though x is logged before it’s declaration. It doesn’t result in an error instead, undefined is logged. Because, variable declaration using var hoisted to the top.

function hoistingEx(){
    console.log(x);
    let x = 10;
    console.log(x);
}

hoistingEx();
ReferenceError: Cannot access 'x' before initialization

In the above example, behavior is totally different attempt to logging x before declaration results in ReferenceError because, let variables remains uninitialized in Temporal Dead Zone until their declaration encountered.

Constant const

const introduced in ES6. As it’s name suggests it is used to declare a constant value variable. Redeclaration and reassignment of const variable is not allowed in JS. They need to initialized at time of declaration only. Variables declared with const keyword cannot be hoisted and block scoped.

function constEx(){
    const PI = 3.14;
    console.log(PI);
    PI = 3.1412;
    console.log(PI);
}

constEx();
3.14
TypeError: Assignment to constant variable.

Though, reassignment is not allow for const variable. They are not immutable means, it is possible to modify the properties of arrays and objects assigned with const keyword.

const person = {
    name: 'John',
    age: 30
};
person.age = 31;
console.log(person);
{ name: 'John', age: 31 }

In summary, let addresses several disadvantages of var which leads to more predictable and maintainable code code. Therefore, it is recommended to use let or const as per the use case over var keyword in modern JavaScript.

You may also like...

Leave a Reply

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