ES6 Block Bindings

Nahid Hossain Nehal
3 min readNov 3, 2020

Binding

In programming, binding means to declare or initialize a variable by var, const, or let because when we declare or initialize a value that means we bind a value with a name.
By ECMAScript-6 it is easier to manipulate the scope.

Var Declarations and Hoisting

Before talking about var declaration let’s know about hoisting….

Hoisting means to raise something top. We hoist chandeliers on the ceiling in our home or office so that we can see it from any corner.

In the same way in javascript variables become hoisting so that we can access the variable from everywhere and it happens when we declare a variable as a var. Let’s see an example.

function setValue(condition) {

if (condition) {
var name = "nahid";

// do something

return name;
} else {

// name exists here with a value of undefined

return null;
}

// name exists here with a value of undefined
}

In this example, we declared the “name” variable as a var that’s why we can access this “name” variable from between the else clause but into else clause name variables value is undefined because the hoisting doesn’t hoist the initialization part it only hoist the variable name and initialization part remain in the same place.

Block Level Declarations

If we declare a variable in a block scope by let or const we could not access that variable from outside of that block scope. Block scope can create through the following methods:

  • Inside a function (function block)
  • Inside a block (wrapped with two curly { } braces)

We all ready use the block scope in the previous example by using var, but this time we are going to use let instead of var

function setValue(condition) {

if (condition) {
let name = "nahid";

// do something

return name;
} else {

// value doesn't exist here

return null;
}

// value doesn't exist here
}

In this example we can see by using let variable can’t access into other block.

By using let and const variables become unable to access out side of that block.

Block Binding in Loops

Before discuss about “block binding in loops” let’s see an loops example by using var

for (var i=0; i < 10; i++) {
// something........
}

// i is still accessible here
console.log(i); // 10

in this example we can see that variable i is accessible after completed the loop because the var declaration gets hoisted. Let’s use let instead of var

for (let i=0; i < 10; i++) {
process(items[i]);
}

// i is not accessible here - throws an error
console.log(i);

here we can see i is not accessible after the loop completed because once loop is complete the variable is destroyed.

Emerging Best Practices for Block Bindings

After realise ECMAScript-6 the best practice is using const and let instead of var. Most of time we will use const by default and only use let when we know that a variable's value needs to change.

--

--