learn deep. ship safe.Practice testsFollow ByteMunSubscribe

Concept

Variables and scope

Where a variable can be read: global, function and block scope, and how let, const and var differ.

Variables and scope explained

Scope decides where in your code a variable can be read or changed. JavaScript has global scope, function scope and block scope: var belongs to the nearest function, while let and const belong to the nearest block, the code between { and }. Scope is lexical, which means it is fixed by where the code is written, not by where a function is called from.

How scope works

When code reads a name, JavaScript looks in the current scope, then the enclosing one, and so on out to the global scope. This chain is what lets inner functions use outer variables, and it is the foundation of closures.

const site = "ByteMuni";          // global
function greet(user) {             // function scope
  if (user) {
    const msg = `Hi ${user}`;      // block scope
    console.log(msg, site);        // can see msg, user and site
  }
  // console.log(msg);  ReferenceError: msg only exists inside the if block
}

var, let and const

  • var: function-scoped, can be redeclared, and hoisted with the value undefined.
  • let: block-scoped, can be reassigned, cannot be used before its declaration line.
  • const: block-scoped and cannot be reassigned. The value itself can still change if it is an object or array.

Common mistakes

  • Shadowing by accident: declaring a variable with the same name as an outer one hides the outer one inside that block.
  • Leaking globals: assigning to an undeclared name in sloppy mode creates a global. Modules and strict mode make it an error instead.
  • Using var in loops with callbacks: every callback shares one variable. Use let.

What interviewers ask about scope

  • "What is the difference between var, let and const?" Scope, redeclaration, reassignment and hoisting behaviour.
  • "What is lexical scope?" Scope fixed by where code is written, which is why closures remember their surroundings.
  • "Predict the output" of nested functions that reuse a variable name, explaining which binding each line sees.
Concept map
Variables and scope
Then learnClosures

What to learn after Variables and scope

  • ClosuresClosures are functions remembering their scope, so scope comes first.

Connections to other concepts

Related
Hoisting

Practise Variables and scope

All topics