How JavaScript Works: Execution Examples
How JavaScript works demonstrated through practical code examples showing execution order, scope, and asynchronous behavior.
How JavaScript Works: Execution Examples
Understanding how JavaScript works requires seeing it in action. These practical examples demonstrate JavaScript's execution model, including synchronous processing, asynchronous operations, and scope behavior.
Basic Execution Order Example #
This example shows how JavaScript works with basic synchronous code execution:
Asynchronous Execution Demonstration #
This example illustrates how JavaScript works with asynchronous operations and the event loop:
Variable Hoisting Behavior #
See how JavaScript works with variable declarations and the temporal dead zone:
// Variable hoisting with var
console.log("var example:");
console.log(hoistedVar); // undefined (not error)
var hoistedVar = "I'm hoisted!";
console.log(hoistedVar); // "I'm hoisted!"
// Temporal dead zone with let/const
console.log("let example:");
try {
console.log(notHoisted); // ReferenceError
} catch (e) {
console.log("Error:", e.message);
}
let notHoisted = "I'm in TDZ until declared";
Function Hoisting Examples #
How JavaScript works with different function declaration styles:
Scope Chain Example #
This demonstrates how JavaScript works with scope resolution:
Event Loop Visualization #
Complex example showing how JavaScript works with multiple asynchronous operations:
// Event loop priority demonstration
console.log("Start");
// Macro task (lowest priority)
setTimeout(() => console.log("Timeout 1"), 0);
// Micro task (high priority)
Promise.resolve().then(() => {
console.log("Promise 1");
return Promise.resolve();
}).then(() => {
console.log("Promise 2");
});
// Another macro task
setTimeout(() => console.log("Timeout 2"), 0);
// Immediate execution
console.log("End");
// Output order: Start, End, Promise 1, Promise 2, Timeout 1, Timeout 2
Closure Demonstration #
How JavaScript works with closures and lexical scoping:
This Binding Example #
Understanding how JavaScript works with this
context:
const obj = {
name: "Object",
regularFunction: function() {
console.log("Regular function this:", this.name);
},
arrowFunction: () => {
console.log("Arrow function this:", this.name);
}
};
obj.regularFunction(); // "Object" (method call)
obj.arrowFunction(); // undefined (lexical this)
const extracted = obj.regularFunction;
extracted(); // undefined (function call, not method)
Performance Optimization Example #
How JavaScript works with engine optimizations:
Usage Tips #
- Run these examples to see how JavaScript works in practice
- Modify values and observe different behaviors
- Use browser dev tools to debug execution flow
- Practice predicting output before running code
Related Resources #
These examples demonstrate the core principles of how JavaScript works, from basic execution to complex asynchronous patterns.