JavaScript and TypeScript course ยท Module 2: Functions, Arrays and Objects
Hoisting in JavaScript
In this lesson8
Welcome back to Jurassic Park! In the lesson on variable scope we examined where a variable lives, that is, what scope it has. Today we will answer an equally important question: from which moment a variable or a function exists at all. The mechanism that decides this is called hoisting, and knowing it protects you from the sneakiest category of bugs in the park systems - the kind that do not blow anything up, but quietly hand over the wrong value. A variable that exists but holds nothing can be more dangerous than a variable that does not exist at all.
What Is Hoisting?
Hoisting (literally "lifting") is JavaScript's behavior of moving variable and function declarations to the top of their scope - function or global - already during the compilation phase, before the first line of code runs. The engine first scans the whole code and makes a list of the names that appear in it, and only then starts executing it. Thanks to this, we can refer to some variables and functions earlier than the place where they were written in the file.
It is a bit like an inventory list drawn up before the dinosaurs arrive in their enclosures: the JavaScript compiler first notes down "what to expect", and only then performs the specific operations, line by line. Only declarations travel to the top - never the values we assign to them.
Every variable goes through the same life cycle. The engine first parses the code, then creates an execution context and reserves memory in it for the declared names (this is exactly the moment of hoisting), and only then executes the code: the variable gets a value and is used. When no reference leads to the value anymore, the garbage collector takes care of the cleanup. In the mark phase it marks everything the program can still reach and treats the rest as ready for removal, and then in the sweep phase it frees that memory.
Function Hoisting
Function declarations are hoisted in their entirety: the function body travels together with the name. So we can call a function before it appears in the file. In park management this is very convenient, because it lets us keep the main logic at the top and push the technical details down to the bottom.
// We can call the function before it is defined
checkSecurity("T-Rex Enclosure"); // "Checking security: T-Rex Enclosure"
// The function declaration is hoisted
function checkSecurity(location) {
console.log(`Checking security: ${location}`);
return true;
}This works because during the compilation phase JavaScript lifts the entire declaration to the top of the scope - the name together with the body. Before the first statement runs, checkSecurity is already a complete function, ready to be called, and not an empty slot waiting to be filled in. This is the only case in the whole language where a value travels to the top of the scope together with the name, because a function is a value too. All the other constructs we are about to see hoist the name alone and nothing else.
Watch Out for Function Expressions!
Only function declarations are hoisted in their entirety. Function expressions, that is, functions assigned to a variable, follow the rules of variable hoisting: the variable itself goes to the top, but the function assigned to it does not.
// This will NOT work correctly
// feedDinosaur("Rex"); // TypeError: feedDinosaur is not a function
// Only the variable declaration is hoisted, not the function assignment
var feedDinosaur = function(dinoName) {
console.log(`Feeding dinosaur: ${dinoName}`);
};
// From this line on we can call the function
feedDinosaur("Rex"); // "Feeding dinosaur: Rex"Read the error message carefully, because it is a valuable clue. We do not get a ReferenceError, but TypeError: feedDinosaur is not a function - the name feedDinosaur already exists, it simply holds undefined at that moment, and undefined cannot be called like a function. This small difference can cut debugging from an hour to a minute: a ReferenceError points us to a typo or a forgotten import, while a TypeError points us to the order of the lines in the file. A function declaration is available throughout its whole scope, a function expression only from the line with the assignment.
Arrow Functions Work the Same Way
Arrow functions are expressions too, so their body is never hoisted. Because we usually assign them to const or let, the error for calling them too early turns out to be even firmer than with var.
// checkFence(); // ReferenceError: Cannot access checkFence before initialization
const checkFence = () => "Fence OK";
console.log(checkFence()); // "Fence OK"The difference matters: with var we got a TypeError, here a ReferenceError. Both messages mean the same thing - "too early" - but the const version stops the program exactly at the spot of the mistake, instead of passing along an undefined value that will blow up a few dozen lines later, in a completely innocent piece of code. Hence the practical rule: before the line with the definition, you can only use functions declared with function name() {}. Everything we assign to a variable - a classic function expression or an arrow - works only below that line.
Variable Hoisting
With variables, hoisting behaves differently depending on the keyword (var, let, const). This is where most of the surprises come from, so let's break both cases down into their basic parts.
Hoisting of Variables Declared with var
Variables declared with var are hoisted and immediately initialized with the value undefined, so reading them before the declaration is perfectly legal:
console.log(dinosaurCount); // undefined (not an error!)
var dinosaurCount = 15;
console.log(dinosaurCount); // 15Nothing broke - and that is exactly the problem. The program carries on with a value nobody planned, and undefined in the dinosaur counter turns into NaN in every calculation it ends up in. The report will show NaN instead of the number of animals in an enclosure that holds three, and nobody will get any warning. It is easier to understand if we imagine that before running the code, JavaScript rewrites the code above into this form:
var dinosaurCount; // Hoisting - the declaration travels to the top
console.log(dinosaurCount); // undefined
dinosaurCount = 15; // The assignment stays where we wrote it
console.log(dinosaurCount); // 15The declaration jumped to the top, while the assignment stayed exactly where we wrote it. The whole rule of hoisting fits into one sentence: the declaration travels up, the value does not move from its place. The stretch between these two points is a window in which the variable is reachable but empty. A park sensor reporting undefined looks worryingly similar in the logs to a sensor that reports nothing at all - and those are two completely different situations, one meaning all is calm, the other a broken fence.
Hoisting of Variables Declared with let and const
Variables declared with let and const (introduced in ES6) are hoisted too, but they do not get the value undefined. Instead, they land in the temporal dead zone (TDZ) - the period from the moment the block starts executing up to the line in which the variable is actually declared. Reaching for the variable during that time ends with an error.
// This will cause an error:
// console.log(securityLevel); // ReferenceError: Cannot access securityLevel before initialization
let securityLevel = "High";
console.log(securityLevel); // "High"
// The same applies to const:
// console.log(parkName); // ReferenceError: Cannot access parkName before initialization
const parkName = "Jurassic Park";
console.log(parkName); // "Jurassic Park"You need to be able to tell two error messages apart:
- a variable that was never declared:
ReferenceError: xyz is not defined - a
letorconstvariable in the temporal dead zone:ReferenceError: Cannot access 'xyz' before initialization
This distinction is a gift for whoever is debugging. The first case means the variable does not exist anywhere - most likely a typo or a forgotten import. The second says the variable exists, we just reached for it too early, so it is enough to move the read below the declaration. Imagine a two-hundred-line function in which a value is read at the top and assigned at the bottom: with var we get a silent undefined and an hour of groping around in the dark, with let the program stops immediately and points a finger at the exact line. The temporal dead zone is not a limitation, but an early warning system.
Classes Also Sit in the Temporal Dead Zone
Classes behave like let and const, not like function declarations. Their name is hoisted, but until the engine executes the class body, every attempt to use the class ends with an error.
// const dino = new Dinosaur("Rex"); // ReferenceError: Cannot access Dinosaur before initialization
class Dinosaur {
constructor(name) {
this.name = name;
}
}
const dino = new Dinosaur("Rex"); // OK
console.log(dino.name); // "Rex"So the rule "functions can be defined below the place where they are used" does not extend to classes - a class must be created before the first new that creates an instance of it. If out of habit you push the class definition to the end of the file, this is exactly the message you will see in the console, and the cure is trivial: move the class above the code that instantiates it. In the park's files this gives a simple order - first the models of animals and equipment, then the logic that uses them, and never the other way round.
Hoisting and Variable Scope
Hoisting is tightly intertwined with variable scope. Declarations do not travel to the top of the file, but to the top of their own scope, and which scope counts as "their own" depends on the keyword: var sticks to function scope, let and const to block scope. In the global scope the rule stays the same, except that the top is simply the beginning of the program.
Example with var (Function Scope)
var completely ignores the braces of an if or a loop: the declaration lands at the top of the function that contains it, no matter where we wrote it.
function monitorSystem() {
console.log(systemStatus); // undefined (hoisting within the function)
if (true) {
var systemStatus = "Online";
}
console.log(systemStatus); // "Online"
}
monitorSystem();
// console.log(systemStatus); // ReferenceError: systemStatus is not defined (outside the function scope)The if block did not create a new scope for systemStatus here at all. The declaration jumped to the top of monitorSystem, so the variable can be read even before the block (it is empty at that point), and after the block it already holds the assigned value. Outside the function it disappears completely, because the only boundary that var respects is a function. So two console.log calls with the same name give two different results - not because there are two variables, but because we look at one variable once before the assignment and once after it.
Loops Show the Difference Most Clearly
Loops are the best testing ground for comparing both scopes, because the counter is declared and used in one place. Check what remains after a loop whose counter is created with var, and what remains after a loop with let.
for (var index = 0; index < 3; index++) {
// patrolling the enclosures
}
console.log(index); // 3 - var survives the loop (function scope)
for (let step = 0; step < 3; step++) {
// patrolling the enclosures
}
// console.log(step); // ReferenceError - let stays in block scopeAfter the first loop finishes, index still has the value 3, because it belongs to the function scope and calmly survives the closing brace. The step variable from the second loop has block scope and disappears together with the loop, so reading it below ends with a ReferenceError. This difference is behind the famous counter troubles in loops with a delay: with var all the calls see the same final value, with let each iteration gets its own copy of the counter and keeps its own value.
Example with let and const (Block Scope)
With let and const, every pair of braces creates a new scope, and the temporal dead zone applies to that very block, not to the whole function.
function checkEnclosures() {
// console.log(enclosureStatus); // ReferenceError (temporal dead zone)
if (true) {
let enclosureStatus = "Secure";
console.log(enclosureStatus); // "Secure"
}
// console.log(enclosureStatus); // ReferenceError (outside the block scope)
}
checkEnclosures();Both commented-out lines would end with an error, but for completely different reasons: the first because the variable is still sitting in the temporal dead zone, the second because the if block has ended and the variable has ceased to exist. The braces are a real wall here, and that is exactly what we want - a block variable stays in its own enclosure. In the exercise waiting for you right after this lesson, you will practice variable scope in different contexts: you will create variables with different scopes - global, function and block - and observe how they behave.
Practical Examples of Hoisting in Jurassic Park
Example 1: Dinosaur Monitoring System
Function hoisting lets you organize a file by importance rather than by execution order. The main procedure goes at the top, the helper functions it uses at the very bottom - and everything still works.
// Dinosaur monitoring system
// The main functions are defined at the top for clarity
function initMonitoringSystem() {
console.log("Initializing the dinosaur monitoring system...");
// We can call these functions even though they are defined later
const healthStatus = checkDinosaurHealth("Rex");
const locationData = trackDinosaur("Blue");
return {
health: healthStatus,
location: locationData,
systemStatus: "Online"
};
}
// Calling the main function
const systemStatus = initMonitoringSystem();
console.log(systemStatus);
// Helper functions defined at the bottom of the file
function checkDinosaurHealth(dinoName) {
console.log(`Checking the health of dinosaur: ${dinoName}`);
return "Healthy";
}
function trackDinosaur(dinoName) {
console.log(`Tracking dinosaur: ${dinoName}`);
return { x: 135, y: 270, area: "Sector B" };
}The call to initMonitoringSystem falls on a line that none of the helper functions has "reached" yet, and still the code runs without a hitch. This is pure function declaration hoisting: both were complete before the first statement ran. Nothing magically moves around while the program is running, and the gain is purely human - whoever opens this file will first read what the system does, and only then how it does it.
Example 2: The Hoisting Trap
The same mechanism can work against us. Hoisting becomes treacherous when an inner function declares a variable with a name that already exists in the outer scope. Read the code carefully and try to predict the result before you look at the explanation.
// A trap related to hoisting
// Function that checks the security measures
function checkSecurity() {
var fenceStatus = "Offline"; // Hoisted to the top of the function
function enableFences() {
// The local variable is hoisted to the top of enableFences,
// but it has no value at all until the initialization line
console.log("Current fence status before the change:", fenceStatus); // undefined!
// The local fenceStatus variable shadows the one from the outer scope
var fenceStatus = "Online";
console.log("New fence status:", fenceStatus); // "Online"
}
enableFences();
console.log("Fence status in the main function:", fenceStatus); // "Offline" (not changed)
}
checkSecurity();A subtle trap is hidden here: the console.log inside enableFences prints undefined, because the local fenceStatus variable was hoisted to the top of the inner function and shadows the one from the outer scope from the very first line, even though it only gets its value further down. The outer variable never changes either - it keeps the value "Offline" to the end. In a real park this would look like the operator panel announcing that the fences are switched on, while the main security function still considers them switched off.
Example 3: A Better Approach with let and const
Replacing var with let and const eliminates this whole class of problems, because reading too early stops the program instead of quietly producing undefined.
// A better approach using let and const
function parkOperations() {
// We use const for values that should not change
const maxVisitors = 2000;
// We use let for variables that will change
let currentVisitors = 0;
function admitVisitors(count) {
// With let and const, reading a variable before its declaration ends with an error,
// which makes it much easier to catch the problem
// This would cause an error:
// console.log(availableSpace); // ReferenceError: Cannot access before initialization
// First we declare, then we use
const availableSpace = maxVisitors - currentVisitors;
if (count <= availableSpace) {
currentVisitors += count;
console.log(`Admitted ${count} visitors. Currently in the park: ${currentVisitors}`);
return true;
}
console.log(`Too many visitors! Available places: ${availableSpace}`);
return false;
}
// Testing our function
admitVisitors(500); // Admitted 500 visitors
admitVisitors(1000); // Admitted 1000 visitors
admitVisitors(700); // Too many visitors! Available places: 500
return currentVisitors;
}
console.log(`Total number of visitors: ${parkOperations()}`);Let's check what has not changed here: maxVisitors and currentVisitors are still hoisted, because every declaration is subject to hoisting. What has changed is the reaction to a mistake - the temporal dead zone turns a read that comes too early into a loud error instead of a discreet undefined. Every value is created exactly where it is needed, and not a moment earlier, so the gate logic reads from top to bottom without you having to keep the hoisting rules in your head. That is what it is all about in practice: not memorizing the mechanism, but writing code in which the mechanism never surprises you.
Practical Tips About Hoisting
Always declare variables at the top of their scope - this minimizes hoisting-related problems and makes the code much easier to read.
Prefer
letandconstovervar- errors from the temporal dead zone are incomparably easier to diagnose than mysteriousundefinedvalues that surface a few hundred lines later.Declare functions before you use them - function hoisting works, but the natural reading order still remains the clearest for the person who comes back to this code in six months.
Avoid function declarations inside conditional blocks - the behavior can differ between environments, so in that case it is safer to use a function expression assigned to a variable.
Remember that hoisting applies to declarations, not to initialization - a value is assigned exactly where we wrote the assignment, never earlier.
A Bigger Example: The Park Incident Management System
Below you will find a more complete incident management system for Jurassic Park, which brings together everything from this lesson in one place: hoisted function declarations, a var variable at module level, and let and const used for state that changes and for state that must not change.
// Jurassic Park incident management system
// Using hoisting - we declare the variables at the beginning
var activeIncidents = [];
let alertLevel = "Normal";
const MAX_INCIDENTS = 5;
// The main function for initializing the system
function initIncidentSystem() {
// This variable is hoisted only within this function
var systemStatus = "Initializing";
// We use function hoisting - we can call them before their definition
logSystemStatus();
resetIncidents();
systemStatus = "Online";
logSystemStatus();
// A local function - visible only inside initIncidentSystem
function logSystemStatus() {
console.log(`System status: ${systemStatus}`);
}
return {
reportIncident, // A reference to a function defined below
checkAlertLevel, // A function defined below
getActiveIncidents, // A function defined below
resetIncidents // A function defined inside initIncidentSystem
};
// A local function that we return as part of the API
function resetIncidents() {
console.log("Resetting the incident list...");
activeIncidents = [];
updateAlertLevel();
}
}
// Function declarations are hoisted, so they can be called before their definition
// Function for reporting a new incident
function reportIncident(location, type, severity) {
console.log(`Incident report: ${type} at location ${location} (threat level: ${severity})`);
const incident = {
id: generateIncidentId(),
location,
type,
severity,
timestamp: new Date().toISOString(),
status: "Active"
};
activeIncidents.push(incident);
if (activeIncidents.length > MAX_INCIDENTS) {
declareEmergency();
} else {
updateAlertLevel();
}
return incident;
}
// Generating a unique incident ID
function generateIncidentId() {
return `INC-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
}
// Updating the alert level based on the active incidents
function updateAlertLevel() {
const highSeverityCount = activeIncidents.filter(inc => inc.severity === "High").length;
if (highSeverityCount >= 3) {
alertLevel = "Critical";
} else if (highSeverityCount > 0 || activeIncidents.length >= 3) {
alertLevel = "Elevated";
} else if (activeIncidents.length > 0) {
alertLevel = "Caution";
} else {
alertLevel = "Normal";
}
console.log(`Alert level updated: ${alertLevel}`);
}
// Function called when there are too many incidents
function declareEmergency() {
alertLevel = "Evacuation";
console.log("WARNING! Too many active incidents. We are declaring a park evacuation!");
// Code for initiating the evacuation protocols...
}
// Function for checking the current alert level
function checkAlertLevel() {
return {
level: alertLevel,
incidentCount: activeIncidents.length,
timestamp: new Date().toISOString()
};
}
// Function that returns the list of active incidents
function getActiveIncidents() {
return [...activeIncidents]; // We return a copy so that nobody modifies the original
}
// Initializing the system
const incidentSystem = initIncidentSystem();
// Testing the system
console.log("===== TESTING THE INCIDENT MANAGEMENT SYSTEM =====");
// Checking the initial state
console.log("Initial alert level:", incidentSystem.checkAlertLevel().level);
// Reporting incidents
incidentSystem.reportIncident("T-Rex Enclosure", "Fence damage", "High");
incidentSystem.reportIncident("Visitor Center", "Power outage", "Medium");
// Checking the state after the reports
console.log("Active incidents:", incidentSystem.getActiveIncidents().length);
console.log("Current alert level:", incidentSystem.checkAlertLevel().level);
// Adding more high-priority incidents
incidentSystem.reportIncident("Laboratory", "Genetic material leak", "High");
incidentSystem.reportIncident("Velociraptor Enclosure", "Escape attempt", "High");
// This should trigger the evacuation state
incidentSystem.reportIncident("Sector B", "Dinosaur outside the enclosure", "High");
incidentSystem.reportIncident("Operations Center", "Security system failure", "High");
// Resetting the system
incidentSystem.resetIncidents();
console.log("After the reset - alert level:", incidentSystem.checkAlertLevel().level);Trace the order of events in this file. initIncidentSystem calls logSystemStatus and resetIncidents before either of them appears in the code, and resetIncidents even sits after the return statement - yet everything works, because function declarations are complete before the first line of the body executes. Variables are a different story: var systemStatus can be read from the very beginning of the function, but it only gets the value "Initializing" on its own line, while activeIncidents, alertLevel and MAX_INCIDENTS were deliberately placed at the very top of the file so that nobody reaches for them too early.
Summary
Hoisting is an important JavaScript concept that shapes the way our code is executed:
Function declarations are hoisted in their entirety - you can use them before the declaration.
var variables are hoisted and initialized with the value
undefined- you can refer to them earlier, but until the assignment they carry no useful value.let and const variables (and classes along with them) are hoisted, but they stay in the temporal dead zone - an attempt to read them before the declaration ends with an error.
Function expressions, including arrow functions, follow the rules for variables - the variable is hoisted, the assigned function is not.
Understanding hoisting is key to writing predictable JavaScript code. It works exactly like in Jurassic Park itself - knowing the rules and protocols is enough for the day to pass without surprises or dangerous situations.
"Hoisting in JavaScript is like the park's morning start-up," says Dr. Rex. "Before the visitors arrive, before the code runs, part of the preparation happens on its own: the protocols are ready, the procedures are in place. But the real data still has to be collected as you go, and reaching for it too early will tell you absolutely nothing!"
In one of the next lessons we will take a close look at the this keyword - another fundamental element of JavaScript, and one that can cause quite a bit of confusion.
Code for this lesson: index.js
// Hoisting in JavaScript - Jurassic Park
console.log("Hoisting Laboratory");
console.log("Understanding hoisting in JavaScript\n");
// ===========================================
// 1. WHAT IS HOISTING?
// ===========================================
console.log("=== 1. Introduction to hoisting ===");
// JavaScript "hoists" declarations to the top of the scope
// We can use a function before its declaration!
roarDinosaur("T-Rex"); // Works!
function roarDinosaur(name) {
console.log(`${name} says: ROAAARRR!`);
}
roarDinosaur("Velociraptor");
console.log("\nThe function works before its declaration thanks to hoisting!");
// ===========================================
// 2. FUNCTION HOISTING
// ===========================================
console.log("\n=== 2. Function hoisting ===");
// Function declarations are hoisted
feedDinosaur("Triceratops"); // Works
function feedDinosaur(dino) {
console.log(`Feeding: ${dino}`);
}
// Function expressions are NOT hoisted
// feedDino2("Stegosaurus"); // ERROR!
const feedDino2 = function(dino) {
console.log(`Feeding: ${dino}`);
};
feedDino2("Stegosaurus"); // Now works
// Arrow functions are also NOT hoisted
// feedDino3("Brachiosaurus"); // ERROR!
const feedDino3 = (dino) => {
console.log(`Feeding: ${dino}`);
};
feedDino3("Brachiosaurus"); // Now works
// ===========================================
// 3. VAR HOISTING
// ===========================================
console.log("\n=== 3. Hoisting var variables ===");
console.log("\nBefore declaration:");
console.log("dinoName:", typeof dinoName); // undefined (not an error!)
var dinoName = "T-Rex";
console.log("After declaration:");
console.log("dinoName:", dinoName); // T-Rex
// JavaScript actually interprets this as:
// var dinoName; // Declaration hoisted to the top
// console.log(dinoName); // undefined
// dinoName = "T-Rex"; // Assignment
// ===========================================
// 4. HOISTING LET AND CONST
// ===========================================
console.log("\n=== 4. Hoisting let and const ===");
// let and const are also hoisted, but...
// are in the "Temporal Dead Zone" (TDZ)
console.log("\nAttempt to use before declaration:");
// console.log(dinoSpecies); // ReferenceError: Cannot access before initialization
// console.log(parkName); // ReferenceError: Cannot access before initialization
let dinoSpecies = "Velociraptor";
const parkName = "Jurassic Park";
console.log("After declaration:");
console.log("dinoSpecies:", dinoSpecies);
console.log("parkName:", parkName);
// ===========================================
// 5. TEMPORAL DEAD ZONE (TDZ)
// ===========================================
console.log("\n=== 5. Temporal Dead Zone (TDZ) ===");
function demonstrateTDZ() {
console.log("\nInside function - before declaration:");
// This zone is the TDZ for 'dinosaur'
// console.log(dinosaur); // ERROR in the TDZ
let dinosaur = "Triceratops";
console.log("After declaration:", dinosaur); // Works
}
demonstrateTDZ();
// ===========================================
// 6. DIFFERENCES: var vs let vs const
// ===========================================
console.log("\n=== 6. Comparison: var vs let vs const ===");
function compareHoisting() {
console.log("\nHoisting test:");
// var - hoisted with value undefined
console.log("var dinosaur1:", typeof dinosaur1); // undefined
var dinosaur1 = "T-Rex";
console.log("var dinosaur1:", dinosaur1); // T-Rex
// let - hoisted, but in the TDZ
// console.log("let dinosaur2:", dinosaur2); // ERROR: TDZ
let dinosaur2 = "Velociraptor";
console.log("let dinosaur2:", dinosaur2); // Velociraptor
// const - hoisted, but in the TDZ
// console.log("const dinosaur3:", dinosaur3); // ERROR: TDZ
const dinosaur3 = "Triceratops";
console.log("const dinosaur3:", dinosaur3); // Triceratops
}
compareHoisting();
// ===========================================
// 7. HOISTING IN BLOCKS
// ===========================================
console.log("\n=== 7. Hoisting in blocks ===");
function blockHoisting() {
console.log("\nBefore the block:");
console.log("globalVar:", typeof globalVar); // undefined
// console.log("blockLet:", typeof blockLet); // ERROR
var globalVar = "Available everywhere";
if (true) {
console.log("\nIn block:");
let blockLet = "Only in the block";
const blockConst = "Only in the block (const)";
console.log("blockLet:", blockLet);
console.log("blockConst:", blockConst);
console.log("globalVar:", globalVar);
}
console.log("\nAfter block:");
console.log("globalVar:", globalVar); // Works
// console.log("blockLet:", blockLet); // ERROR
// console.log("blockConst:", blockConst); // ERROR
}
blockHoisting();
// ===========================================
// 8. HOISTING IN LOOPS
// ===========================================
console.log("\n=== 8. Hoisting in loops ===");
console.log("\nLoop with var:");
for (var i = 0; i < 3; i++) {
console.log(` Iteration ${i + 1}`);
}
console.log("After loop - i:", i); // Works (i = 3)
console.log("\nLoop with let:");
for (let j = 0; j < 3; j++) {
console.log(` Iteration ${j + 1}`);
}
// console.log("After loop - j:", j); // ERROR: j is not defined
// ===========================================
// 9. PRACTICAL HOISTING PROBLEMS
// ===========================================
console.log("\n=== 9. Common pitfalls ===");
// Problem 1: Overriding function
function problemExample1() {
console.log("\nProblem 1: Overriding");
function greet() {
console.log(" First greeting");
}
greet(); // Which function will be called?
function greet() {
console.log(" Second greeting (this will be used!)");
}
// JavaScript "hoists" both declarations,
// but the second overrides the first
}
problemExample1();
// Problem 2: var in a loop with setTimeout
console.log("\nProblem 2: var in a loop with setTimeout");
console.log("With var (all will show 3):");
for (var k = 0; k < 3; k++) {
setTimeout(function() {
console.log(` var k = ${k}`);
}, 100);
}
setTimeout(() => {
console.log("\nWith let (will show 0, 1, 2):");
for (let m = 0; m < 3; m++) {
setTimeout(function() {
console.log(` let m = ${m}`);
}, 100);
}
}, 200);
// ===========================================
// 10. BEST PRACTICES
// ===========================================
console.log("\n=== 10. Best practices ===");
// BEST PRACTICES:
// 1. Declare variables at the beginning of scope
function goodPractice1() {
const parkName = "Jurassic Park";
let dinosaurCount = 0;
let totalVisitors = 0;
dinosaurCount = 15;
totalVisitors = 1000;
console.log(`\n${parkName}: ${dinosaurCount} dinosaurs, ${totalVisitors} visitors`);
}
goodPractice1();
// 2. Use const by default, let when needed
const SECURITY_LEVEL = "HIGH";
let currentStatus = "OPERATIONAL";
console.log(`Security: ${SECURITY_LEVEL}`);
console.log(`Status: ${currentStatus}`);
// 3. Avoid var
// var oldWay = "Don't use this!"; // BAD
// 4. Declare functions before use (readability)
function wellOrganized() {
// Declarations at the beginning
const MAX_CAPACITY = 50;
let currentCapacity = 0;
// Helper functions
function addDinosaur(name) {
if (currentCapacity < MAX_CAPACITY) {
currentCapacity++;
console.log(` Added ${name}. Capacity: ${currentCapacity}/${MAX_CAPACITY}`);
} else {
console.log(` No space for ${name}`);
}
}
// Main logic
console.log("\nSystem capacity management:");
addDinosaur("T-Rex");
addDinosaur("Velociraptor");
addDinosaur("Triceratops");
}
wellOrganized();
// ===========================================
// 11. COMPLEX EXAMPLE
// ===========================================
console.log("\n=== 11. Monitoring system - complex example ===");
function createMonitoringSystem() {
// Declarations at the beginning (best practice)
const systemName = "Dino Monitor v1.0";
let isActive = false;
let alertCount = 0;
// Helper functions
function activate() {
isActive = true;
console.log(`\n${systemName} activated`);
}
function deactivate() {
isActive = false;
console.log(`${systemName} deactivated`);
}
function sendAlert(message) {
if (isActive) {
alertCount++;
console.log(`Alert #${alertCount}: ${message}`);
} else {
console.log("System inactive - alert skipped");
}
}
function getStats() {
console.log(`\nStatistics for ${systemName}:`);
console.log(` Status: ${isActive ? "Active" : "Inactive"}`);
console.log(` Alerts sent: ${alertCount}`);
}
// Main interface
return {
start: activate,
stop: deactivate,
alert: sendAlert,
stats: getStats
};
}
const monitor = createMonitoringSystem();
monitor.alert("Test before activation"); // Skipped
monitor.start();
monitor.alert("T-Rex is approaching the fence");
monitor.alert("Security level critical");
monitor.stats();
monitor.stop();
monitor.alert("Test after deactivation"); // Skipped
monitor.stats();
console.log("\nCongratulations! You've mastered hoisting in JavaScript!");Docs entries used in this lesson
Spotted a mistake in this lesson?
Hands-on tasks in the game
- Code editor
Declare a global constant parkName = 'Jurassic Park'. Write a function checkEnclosure() that creates a local constant enclosureName = 'Zone A' and, inside an if (true) block, creates a variable alarmLevel = 5 with let and displays parkName, enclosureName and alarmLevel in the console. The function returns enclosureName. Call checkEnclosure(). Outside the function, enclosureName and alarmLevel must not exist.