Understanding JavaScript Concepts
Grok
July 3, 2025
Contents
1 Introduction 2
2 Polyfill 3
3 Execution Context 3
3.1 Local and Global Contexts . . . . . . . . . . . . . . . . . . . . . . . . . . 3
4 Call Stack 3
5 Web APIs 3
6 Task Queue 4
7 Starvation in JavaScript 4
8 Coercion 4
9 Truthy and Falsy 4
10 Hoisting 4
11 Temporal Dead Zone (TDZ) 4
12 Scopes 5
13 Closures 5
14 this Keyword 5
15 Prototype Inheritance 6
16 Event Loop and Call Stack 6
17 Optional Chaining (?.) 6
18 Destructuring 6
1
19 Promises 6
20 Nullish Coalescing (??) 7
21 IIFE 7
22 Currying 7
23 Memoization 7
24 Modules (import/export) 7
25 Call by Value 8
26 Call by Reference 8
27 Types 8
28 Object 8
29 Immutability 8
30 Deep Cloning 9
31 Common Pitfalls 9
32 Rest and Spread 9
33 .reduce() 9
34 Map and Set 9
35 Higher-Order Functions 10
36 Execution Context in JavaScript 10
37 Object Literals 10
38 Constructor Function 10
39 Recursive Functions 10
40 Conclusion 10
1 Introduction
This document explains key JavaScript concepts, from basic to advanced, with
examples to aid understanding. Each section provides a concise overview suit-
able for beginner to intermediate learners.
2
2 Polyfill
A polyfill is code that implements a feature in browsers that lack support for it,
ensuring compatibility.
if (!Array.prototype.includes) {
Array.prototype.includes = function(element) {
return this.indexOf(element) !== -1;
};
}
3 Execution Context
An execution context is the environment in which JavaScript code runs, manag-
ing variable scope and execution.
3.1 Local and Global Contexts
• Global: The default context, containing global variables and functions.
• Local: Created for each function call, with its own variables.
let globalVar = ”I’m global”;
function example() {
let localVar = ”I’m local”;
console.log(globalVar, localVar); // Accessible
}
4 Call Stack
The call stack tracks function execution. When a function is called, it’s pushed
onto the stack; when it returns, it’s popped off.
function first() { second(); }
function second() { console.log(”Called”); }
first(); // Call stack: first -> second
5 Web APIs
Web APIs (e.g., DOM, setTimeout) are browser-provided features, not part of
core JavaScript, used for tasks like timers or HTTP requests.
setTimeout(() => console.log(”Delayed”), 1000);
3
6 Task Queue
The task queue holds asynchronous tasks (e.g., setTimeout callbacks) to be ex-
ecuted after the call stack is empty.
console.log(”Start”);
setTimeout(() => console.log(”Timeout”), 0);
console.log(”End”); // Start, End, Timeout
7 Starvation in JavaScript
Starvation occurs when low-priority tasks in the task queue are delayed by a
continuous stream of high-priority tasks.
8 Coercion
Coercion is JavaScript’s automatic type conversion during operations.
console.log(”5” + 1); // ”51” (string)
console.log(”5” - 1); // 4 (number)
9 Truthy and Falsy
Values are truthy (evaluate to true) or falsy (evaluate to false) in boolean con-
texts.
if (”hello”) { console.log(”Truthy”); } // Truthy
if (0) { console.log(”Falsy”); } // Falsy: false, 0, ””, null,
undefined, NaN
10 Hoisting
Hoisting moves variable and function declarations to the top of their scope dur-
ing compilation.
console.log(x); // undefined
var x = 5;
foo(); // Works
function foo() { console.log(”Hoisted”); }
11 Temporal Dead Zone (TDZ)
The TDZ is the period where let and const variables exist but cannot be ac-
cessed before their declaration.
4
console.log(x); // ReferenceError: x is not defined
let x = 10;
12 Scopes
Scopes define variable accessibility: global, function, or block.
let global = ”global”;
function scopeTest() {
let local = ”local”;
if (true) {
let block = ”block”;
}
console.log(block); // ReferenceError
}
13 Closures
A closure is a function that retains access to its outer scope’s variables even after
the outer function finishes.
function outer() {
let count = 0;
return function inner() {
return ++count;
};
}
let counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
14 this Keyword
this refers to the object executing the current function, depending on the call
context.
const obj = {
name: ”Test”,
getName: function() { return this.name; }
};
console.log(obj.getName()); // Test
5
15 Prototype Inheritance
Objects inherit properties and methods from a prototype. All objects link to
Object.prototype.
function Person(name) { this.name = name; }
Person.prototype.greet = function() { return ‘Hi, ${this.name}‘; };
let p = new Person(”Alice”);
console.log(p.greet()); // Hi, Alice
16 Event Loop and Call Stack
The event loop processes the task queue, moving tasks to the call stack when it’s
empty, enabling asynchronous execution.
17 Optional Chaining (?.)
Optional chaining allows safe property access, returning undefined if a prop-
erty is missing.
const user = { profile: { name: ”Alice” } };
console.log(user?.profile?.name); // Alice
console.log(user?.address?.zip); // undefined
18 Destructuring
Destructuring extracts values from arrays or objects into variables.
const [a, b] = [1, 2]; // a = 1, b = 2
const { name, age } = { name: ”Bob”, age: 30 };
console.log(name, age); // Bob, 30
19 Promises
Promises handle asynchronous operations, with states: pending, fulfilled, or re-
jected.
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve(”Done”), 1000);
});
promise.then(result => console.log(result)); // Done
6
20 Nullish Coalescing (??)
The ?? operator returns the right operand if the left is null or undefined, oth-
erwise the left.
let value = null ?? ”default”; // default
let defined = 0 ?? 42; // 0
21 IIFE
Immediately Invoked Function Expressions (IIFE) are functions that run imme-
diately after definition, often for scoping.
(function() {
let secret = ”hidden”;
console.log(secret); // hidden
})();
22 Currying
Currying transforms a function with multiple arguments into a sequence of single-
argument functions.
function curry(f) {
return a => b => f(a, b);
}
let add = curry((a, b) => a + b);
console.log(add(2)(3)); // 5
23 Memoization
Memoization caches function results to optimize performance for expensive com-
putations.
function memoize(fn) {
const cache = {};
return x => cache[x] ?? (cache[x] = fn(x));
}
let fib = memoize(n => n <= 1 ? n : fib(n - 1) + fib(n - 2));
24 Modules (import/export)
Modules allow code organization using import and export.
7
// math.js
export const add = (a, b) => a + b;
// main.js
import { add } from ’./math.js’;
console.log(add(2, 3)); // 5
25 Call by Value
Primitive types are passed by value; changes to parameters don’t affect the orig-
inal.
let x = 10;
function change(y) { y = 20; }
change(x);
console.log(x); // 10
26 Call by Reference
Objects are passed by reference; changes to their properties affect the original.
let obj = { value: 10 };
function change(o) { o.value = 20; }
change(obj);
console.log(obj.value); // 20
27 Types
JavaScript has primitive types (number, string, boolean, null, undefined,
bigint, symbol) and objects.
28 Object
Objects are collections of key-value pairs.
let obj = { key: ”value” };
29 Immutability
Immutability prevents object modification. Use Object.freeze for shallow im-
mutability.
8
let obj = Object.freeze({ x: 1 });
obj.x = 2; // Ignored
30 Deep Cloning
Deep cloning copies nested objects, often using JSON.parse(JSON.stringify())
or libraries.
let obj = { a: { b: 1 } };
let clone = JSON.parse(JSON.stringify(obj));
clone.a.b = 2;
console.log(obj.a.b); // 1
31 Common Pitfalls
• Misunderstanding this context.
• Overusing global variables.
• Forgetting async/await with promises.
32 Rest and Spread
Rest collects arguments into an array; spread expands arrays/objects.
function sum(...numbers) { return numbers.reduce((a, b) => a + b); }
let arr = [1, 2];
console.log(sum(...arr)); // 3
33 .reduce()
reduce transforms an array into a single value.
let sum = [1, 2, 3].reduce((acc, curr) => acc + curr, 0); // 6
34 Map and Set
Map stores key-value pairs; Set stores unique values.
let map = new Map([[”key”, ”value”]]);
let set = new Set([1, 2, 2]); // {1, 2}
9
35 Higher-Order Functions
Functions that take or return functions.
function higherOrder(fn) { return fn; }
let greet = higherOrder(() => ”Hello”);
36 Execution Context in JavaScript
See Section 2 for details.
37 Object Literals
Shorthand for creating objects.
let x = 1, y = 2;
let obj = { x, y }; // { x: 1, y: 2 }
38 Constructor Function
Functions used to create objects with new.
function Person(name) { this.name = name; }
let p = new Person(”Alice”);
39 Recursive Functions
Functions that call themselves.
function factorial(n) { return n === 0 ? 1 : n * factorial(n - 1); }
console.log(factorial(5)); // 120
40 Conclusion
These concepts form the foundation of JavaScript programming. Practice them
through projects and refer to https://developer.mozilla.org/en-US/docs/
Web/JavaScript for deeper insights.
10