JavaScript Scope & Hoisting
Understand how variables are scoped and hoisted in JavaScript.
1. Global Scope
Variables declared outside of any function are in the global scope and can be accessed from anywhere.
JavaScript Code
Live JavaScript representation with highlighted changes
var globalVar = "I am global";function checkScope() {console.log(globalVar);}checkScope();
2. Function Scope
Variables declared with var
inside a function are scoped to that function.
JavaScript Code
Live JavaScript representation with highlighted changes
function myFunction() {var functionVar = "I am in a function";console.log(functionVar);}myFunction();// console.log(functionVar); // What happens here?
Challenge!
Uncomment the last line in the code. What do you expect to happen? Why?
3. Block Scope with let and const
let
and const
introduce block scope, which means they are only accessible within the block (the curly braces) they are declared in.
JavaScript Code
Live JavaScript representation with highlighted changes
if (true) {let blockVar = "I am in a block";const alsoBlockVar = "Me too!";console.log(blockVar);console.log(alsoBlockVar);}// console.log(blockVar); // What about here?
4. Hoisting
var
-declared variables are 'hoisted' to the top of their scope. This means you can use a variable before it's declared, but its value will be undefined
.
JavaScript Code
Live JavaScript representation with highlighted changes
console.log(myVar); // What will this log?var myVar = 5;
Console Output