DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Scope in JavaScript(var, let, const)
Emmanuel Os
Emmanuel Os

Posted on

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}`)

Enter fullscreen mode Exit fullscreen mode
  • 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}`)
Enter fullscreen mode Exit fullscreen mode

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}`)
Enter fullscreen mode Exit fullscreen mode
  • 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}`)
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)

This post blew up on DEV in 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!