Why you shouldn't use 'var' anymore!

Why you shouldn't use 'var' anymore!

And how `let` solves a common JavaScript Hoisting

I’ve been using JavaScript ES6 syntax for a while now and One of the first and easiest changes I adapted to was using let/const instead of var. However, I took for granted the benefit let provides over var; it isn’t just a flashy new syntax for var, but rather provides an important scoping mechanism.

let and var both are used in variable creation, but why should you use let instead of var for these situations, if they both provide the basic mutability required of them?

The simple answer is that let provides block-scoping that is absent in the function-scoped var. This explanation obviously begs a practical example.

In this example, what will be printed in the console?

console.log(productId);
var productId = 123;

A novice engineer might answer (incorrectly) that the result is 123. a reasonable analysis, but that victim falls for javascript hoisting.

The correct answer is undefined. Here comes the concept of Hoisting. what is hoisting?

In JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, before execution of the code. In simple words, hoisting allows you to use functions and variables before they're declared.

How to solve this problem?

let gives us a very simple solution.

console.log(productId);
let productId = 123;

That's it - just replace var with let. It gives an error as ReferenceError: Cannot access 'productId' before initialization rather than giving an undefined. This is thanks to the block-scoping behavior of let.

Block Scoping:

for ( let i = 0; i < some_length; i++ ) {
    /* i is defined here */
}
/* i is not defined here * /

while var is functional scoping. below is an example of function scope

// Simple demonstration of function scope.
var n = 1;
function print() {
    console.log(n);
    var n = 2;
    console.log(n);
}
print();
//output
undefined
2

Conclusion

let and const are not just two new cool keywords, they introduced block scope that allows us to write clean and less error-prone code.

Why don’t we use var anymore? Because now there is a better way of declaring variables. With block scope! You don’t need to think twice when declaring variables inside blocks. I think that is easier to work with block scope than with function scope.

Embrace let and const and let var go forever!

I hope you enjoyed it and learned something. Happy coding! :)