Understanding Scope in JavaScript

Scope in JavaScript defines the visibility of variables.

cover for Understanding Scope in JavaScript


In JavaScript the acessibility of variables and functions is defined by the scope. You can access within its scope, but outside of its scope this is not possible.

JavaScript has three types of scope

  • Block scope
  • Function Scope
  • Global Scope

The variables keywords

JavaScript has three keywords we can use to declare a variable. The language had only Global Scope and Function Scope. When ES6 was released it introduced the let and const variables that added the Block Scope to the language.

var

  • Function scope
  • Accepts Hoisting
  • Can be reassigned
  • Can be redeclared

const

  • Block scope
  • Doesn’t accept Hoisting
  • Can’t be reassigned
  • Can’t be redeclared

let

  • Function scope
  • Doesn’t accept Hoisting
  • Can be reassigned
  • Can’t be redeclared

The Scope of variables

We can declare variables using three keywords: var, let and const. Variables declared using const and let have block scope.

Variables declared using var have only global scope, it means that variables declared inside curly braces can be accessed from outside the block.


Global Scope

When the variable is declared outside any block, it has Global Scope, in other words, its visibility is available everywhere. Variables declared with var, const or let has the same availability in the global scope.

const message = "Have a nice day"
const today = new Date().getDate()

// Will output the current day you are reading this article :)
console.log(today)


// will output "Have a nice day" 10 times
for(let i = 0; i < 10; i++) {
  console.log(message)
}

// if the value of the variable today is bigger tha 15, will output "Have a nice day"
if (today >= 15) {
  console.log(message)
}

Block Scope

When the variable is declared inside a block of code, its visibility is available only inside the block where it’s defined, in other words, it’s available just inside curly braces { }.

Examples of Block Statements:

  • if
  • switch
  • for
  • while
if (true) {
  // block statements don't create a new scope
  // this variable has global scope
  var name = "Thiago Nunes Batista"
}

// we can access the variable outside the block statement
// will output "Thiago Nunes Batista"
console.log(name)

With the addition of the let and const keywords to JavaScript, variables declared using this keywords will have local scope inside block statements.

if (true) {
  // this variable has global scope
  var name = "Thiago"

  // this variable has local scope
  const lastName = "Nunes Batista"
}

// we can access this variable outside the block statement
// will output "Thiago Nunes Batista"
console.log(name)

// we can't access this variable because it has local scope
// will thrown an error
console.log(lastName)

Local Scope

Variables declared within a JavaScript funcion are local to the function, it means they can only be accessed from within the function. They are only recognized inside their functions, variables with the same name can be used in different functions.

Variables with this scope are created when a function starts, and deleted when the function is closed. Local scope lives as your functions are beeing executed.

// Global Scope
function firstExample() {
  // Local Scope
}

// Global Scope
function secondExampleFunction() {
  // Local Scope
  function thirdExampleFunction() {
    // Local Scope
  }
}

Function Scope

Every function executation creates a new scope. All variables declared inside this function and the parameters will have local scope, it means they will be available only from within the function and not outside.

Variables having the same name can be used in different functions because because they are bound to their respective functions.

function outputGreetingsMessage(name) {
  // even using the var keyword, the variable message will only be available inside the function scope
  var message = `Hello ${name}`
  console.log(message)
}

// will output the message
outputGreetingsMessage("Thiago")

// will throw an error
console.log(message)

Lexical Scope

In a nested group of function, the inner function have access to the variables and other resources of their parent scope.


Conclusion

It’s very important to master the scope in JavaScript before diving deeper in the language.

References

W3 Schools

MDN