Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Scope

Scope defines the accessibility (visibility) of variables.

JavaScript variables have three types of scope:

  • Block scope
  • Function scope
  • Global scope

Block Scope

Before ES6 (2015), JavaScript variables only had Global Scope and Function Scope.

ES6 introduced two important keywords: let and const.

These keywords enable Block Scope in JavaScript.

Variables declared inside a { } block cannot be accessed from outside that block.

Example

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

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

Variables declared inside a { } block with var can be accessed from outside the block.

Example

{
  var x = 2;
}
// x CAN be used here