Defining Javascript Variables: Why You Should Ditch Var For Let And Const

0
161
Image credit: NordWood Themes

In JavaScript, the use of let and const to define variables is well-known and recommended over the use of var.

This article will elaborate on the reasons for avoiding var and provide guidance on converting old code sourced from the internet, such as StackOverflow, to let/const.

Although it’s not recommended to use var, here’s how you can define a variable using the var keyword:

var name = "Sam";

Let/const is block-scoped

Variables defined with let and const are block-scoped, limiting their accessibility to the closest enclosing block.

The nearest block refers to the nearest pair of opening and closing curly braces. Consider the following example:

function sayHello() { // opening and closing curly braces
    if (true) { // opening and closing curly braces (nearest block)
        const message = "Alex";
    }
}

Since the variable message is block scoped, it is only accessible within the if statement’s curly braces. Any attempt to access message outside of those braces will result in an undefined variable.

This behavior may not come as a surprise to you, as we may have already encountered it while using JavaScript. This is precisely why it’s advised to use let and const instead of var since var is limited to function scope.

Var is function scoped

If you define a variable with var, it will be scoped to the nearest function block.

As an example, if we replace const with var in the previous code:

function sayHello() { // nearest function
    // message is accessible here
    if (true) {
        var message = "Alex";
    }
    // message is also accessible here
}

Since the variable was declared using var, it can be accessed from anywhere within the closest function. However, this is typically not seen as a desirable feature and is considered a flaw in JavaScript’s design.

This behavior is known as hoisting and may come as a surprise to some.

Hoisting & Temporal Dead Zone

Hoisting is a peculiar feature that comes with var defined variables. However, it’s not advisable to depend on this concept, and I am discussing it simply to ensure you’re aware of its existence.

What is hoisting?

Hoisting in JavaScript refers to the practice of moving variables defined within a function to the top of that function.

This occurs whenever you define a variable using var:

function sayHello() {
    console.log(message); // undefined
    var message = "Hello JavaScript.";
    console.log(message); // "Hello JavaScript."
    return message;
}

sayHello();

The code you write will be transpiled by the JavaScript compiler into the following:

function sayHello() {
    var message; // this is hoisting
    console.log(message); // undefined
    message = "Hello JavaScript.";
    console.log(message); // "Hello JavaScript."
    return message;
}

sayHello();

Observe that the JavaScript compiler automatically shifts the variable declaration to the top of the function. This explains why console.log(message) can be accessed before it’s defined, but relying on this behavior is not recommended.

Variables defined with let and const are also hoisted, but they cannot be accessed before initialization since they do not have a default value.

Temporal Dead Zone (TDZ)

The term Temporal Dead Zone refers to the phenomenon where variables declared with let and const cannot be accessed until they’ve been initialized.

console.log(name); // this is the Temporal Dead Zone
let name = "Alex";

The code shown above will result in an error message indicating that the variable name cannot be accessed before it’s declared. Any line of code that attempts to use the name variable before it’s defined will fail due to it being in the Temporal Dead Zone. This is typical behavior that you’d expect from variables.

Converting old code

While searching for JavaScript-related queries, you may come across legacy code that still uses var. In most cases, you can replace var with let, and the code will continue to function as intended. Additionally, you could review the code for variables that are not being reassigned and modify them to use const instead.

Conclusion

In summary, it is recommended to avoid using var in JavaScript and use let or const instead. This is because variables defined with let/const are block-scoped, meaning that they are only accessible within the nearest set of opening and closing curly braces.

On the other hand, the variables defined with var are function scoped and are accessible anywhere within the nearest function. Hoisting is a behavior in JavaScript where variables defined using var are moved to the top of the function, but relying on hoisting is not recommended.

While variables defined with let and const are also hoisted, they cannot be accessed before initialization due to the Temporal Dead Zone. However, in most cases, when working with legacy code from the Internet, var can be swapped with let without causing any issues. Therefore, it is advisable to use let or const to avoid unexpected behavior and errors in your code.


The Web Development and eCommerce Writing Contest is brought to you by Elastic Path in partnership with HackerNoon. Publish your thoughts and experiences on #eCommerce or #web-development to win a cash prize!

Elastic Path is the only commerce company making Composable Commerce accessible for tech teams with unique product merchandising requirements and complex go-to-market strategies. Explore our product today!

By: Sojin Samuel
Originally published at Hackernoon

Source: Cyberpogo



For enquiries, product placements, sponsorships, and collaborations, connect with us at hello@firegulaman.com. We'd love to hear from you!