Variable Scope

Variable scope means where a variable can be recognized and accessed.

Main Types

ScopeMeaning
global scopeavailable across the whole script
local scopeavailable only inside a function or block
block scopeavailable only inside {} when declared with let or const

Example

let globalName = "SpongeBob"
 
function greet() {
  let message = "Hello"
  console.log(message)
  console.log(globalName)
}
 
greet()
console.log(message) // ReferenceError: message is not defined

Remember

  • let and const are block-scoped.
  • var is function-scoped.
  • Prefer let and const because their scope is easier to reason about.