JavaScript Block Bindings (ES6)

Sakibur Rahaman
3 min readMay 8, 2021

What is Binding?

Variable is generally known as binding. When we declare a variable or initialize a variable, we are actually binding a value name inside a scope or a functions. So binding occurs whenever we declare or initialize a variable using var, let, const.

Var Declarations and Hosting

When variable declare with var they are hosting in the top of the functions or global scope, if declare outside of a functions. Var declarations are treated as if they are hoisted to the top of the function (enclosing block) or to the global scope if they are declared outside a function.

We expect when if condition is true then food variable will be created, but the ‘food variable is not dependent on any condition because of the hoisting nature of the var keyword. Behind the scene, JavaScript engine treats the function as follows:

JavaScript engine create a global scope. The food variable hoisted to the top even though the value of the variable stayed on the same spot. That’s why food variable is accessible within the else clause as well as within the function with undefined value.

Block-Level Declarations

We already learned the hoisting nature of var, which may create issues in some cases because of the accessibility of the variable. That’s why block-level declaration comes into picture where declare variables are inaccessible outside of a given block scope. Block scope can be created:

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

Variable declarations using let or const are not hoisted to the top of the enclosing block which can limit the variable’s scope to only the current code block. But if you want the variables are available to the entire block then you can declare the variable using let or const first in the block.

Block Binding in Loops

Block level is very useful when dealing with loops in JavaScript. It is best practice to use let instead of var because var is being hoisted.

--

--