HOW DO YOU DECLARE A VARIABLE IN JAVASCRIPT

Before ECMAScript 2015 specification, the only way to declare a variable in JavaScript was using “var” keyword.

var greeting = "Hello, World!";

The above code snippet will declare a variable named greeting and assigns a value “Hello, World” to it. The ECMAScript 2015 specification introduced other ways to declare a variable - let and const

let greeting = "Hello, World";
const numberOfSeats = 42;

SO, WHAT IS THE DIFFERENCE BETWEEN VAR AND LET

To understand this we will have to understand scopes in JavaScript. Traditionally, JavaScript only had function scopes and global scopes. That is, if you declared a variable or defined a function, it would be either in global scope or in the scope of some other function.

For example,

var iAmGlobalScopedVariable = "Hello, World!";
function foo() {
    var iAmFunctionScopedVariable = 42;
    for (var i = 0; i < 10; i++) {
        var iAmFunctionScopedToo = 42;
    }
}

In the above example, the variable “iAmFunctionScopedToo” is declared in the block of the for-loop. But traditionally, JavaScript would not create a new scope for the block statements. Here, the scope of the variable “iAmFunctionScopedToo” is the function “foo” and not the for-loop’s block. So essentially what we are saying here is, you can use the “iAmFunctionScopedToo” variable outside the for-loop’s block too.

Then came the ECMAScript 2015 specification. It introduced the keywords let and const. These two keywords allowed the variables to be created in the block scope.

For example,

function foo() {
    var iAmFunctionScopedVariable = 42;
    for (var i = 0; i < 10; i++) {
        var iAmFunctionScopedToo = 42;
        let iAmBatman = "naa na…";
    }
}

In the above example, we declared the “iAmBatman” variable using let keyword. This made it a block scoped variable. Block scope means we cannot use it outside its enclosing block (i.e. the for-loop).


REFERENCES

block – JavaScript | MDN: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/block

ECMAScript 2015 Language Specification: https://www.ecma-international.org/ecma-262/6.0/