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
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);show exists, and count exists as undefined: var is hoisted to the top of its scope.count changes from undefined to 1.message is created with the value "outer".show(). Its var shared already exists, as undefined, before any line of show runs.message is a new variable inside show. It hides (shadows) the global message; the global still holds "outer".count > 0 is true, so the if-block runs.note is declared with let inside the if block, so it exists only inside those braces.shared changes from undefined to "whole function".inner inside the if.note is gone, but shared is still here: var belongs to the whole function, not the block.show() has finished, so its variables are gone.message was never touched: "outer".Answer: Not defined. x lives only in the block.
Answer: Yes, they are hoisted
← Arrow Functions, Defaults and Rest · Closures →