Function scope vs Block scope

·

1 min read

The scope is an important concept that manages the availability of variables. The scope is at the base closures, which defines the idea of global and local variables.

Function scope

JavaScript has function scope: Each function creates a new scope. Variables defined inside a function are not accessible (visible) from outside the function. Variables declared with var, let and const are quite similar when declared inside a function.

Block Scope

Before ES6 (2015), JavaScript had only Global Scope and Function Scope. ES6 introduced two important new JavaScript keywords: let and const. These two keywords provide Block Scope in JavaScript. Variables declared inside a { } block cannot be accessed from outside the block:

Example

{
  let x = 2;
}
// x can NOT be used here

Variables declared with the var keyword can not have block scope.