Scope and Hoisting

Where a variable can be seen: the whole file, one function, or one block. And why var behaves differently from let.

JavaScript · beginner · 7 min · 12 steps · free

What you'll learn

Scope.js

var count = 1;
let message = 'outer';

function show() {
  let message = 'inner';
  if (count > 0) {
    let note = 'inside the if';
    var shared = 'whole function';
    console.log(message, note);
  }
  console.log(shared);
}

show();
console.log(message);

Step by step

  1. Before anything runs, show exists, and count exists as undefined: var is hoisted to the top of its scope.
  2. count changes from undefined to 1.
  3. message is created with the value "outer".
  4. JavaScript calls show(). Its var shared already exists, as undefined, before any line of show runs.
  5. This message is a new variable inside show. It hides (shadows) the global message; the global still holds "outer".
  6. count > 0 is true, so the if-block runs.
  7. note is declared with let inside the if block, so it exists only inside those braces.
  8. shared changes from undefined to "whole function".
  9. It prints inner inside the if.
  10. Outside the if block, note is gone, but shared is still here: var belongs to the whole function, not the block.
  11. show() has finished, so its variables are gone.
  12. The global message was never touched: "outer".

Common mistakes

Best practices

Key takeaways

Check yourself

if (true) { let x = 1 } x is?

Answer: Not defined. x lives only in the block.

Function declarations can be called before their line?

Answer: Yes, they are hoisted

·

More in Functions