Scope in JavaScript(var, let, const)

Scope in JavaScript is divided into the Block Scope, Function Scope and the Global Scope.

Starting with the Global Scope

// Global scope
var a = 1;
let b = 2
const c = 3
console.log(`Global Scope ${a} ${b} ${c}`)
  • This is a global scope and everything is fine, if you console.log the value

Function Scope

// Global scope
var a = 1
let b = 2
const c = 3

//Function scope
function num() {
  var a = 10
  let b = 22
  const c = 5
  console.log(`Function Scope ${a} ${b} ${c}`)
}
num()

console.log(`Global Scope ${a} ${b} ${c}`)

So inside the function scope we get our 10, 22, 5 while in the global scope we still get our 1, 2, 3, because they are different variables in different scope.

  • Var is a Function scope It means they are only available inside the function they’re created in, or if not created inside a function, they are ‘globally scoped..
var a = 1;
let b = 2
const c = 3

for(var a = 0; a < 10; a++) {
  console.log(a)
}
console.log(`Global Scope ${a} ${b} ${c}`)
  • The value of var a = 10 in the global scope.
  • The var a in the loop actually changes the value var a in the global scope which is not good, that's the reason let and const was created.

NOTE: var is kind of wired, that's one of the thing that lot of people didn't like about JavaScript. it causes security risks and it can cause confusion if you have some variables in the global scope.

Block Scope

// Global scope
var a = 1
let b = 2
const c = 3

// Block Scope
if(true) {
  var a = 6
  let b = 7
  const c = 10
  console.log(`Block Scope ${a} ${b} ${c}`)
}
console.log(`Global Scope ${a} ${b} ${c}`)

What do you think the global scope var a result will be?

  • The result will be var a = 6 because after declaring the var a = 1 on the global scope it was change in the block scope.

  • Notice the let and const didn't change, in the global scope they retain their values and also in the block scope.

Benefit of let & const

  • They aren't scoped to the function, they are scoped to the block.
  • What is the block? A block is a set of opening and closing curly brackets.

Points to Take

  • var is function scope.
  • let and const are block scope.
  • Function scope is within the function.
  • Block scope is within curly brackets.