0% found this document useful (0 votes)
18 views13 pages

Js All in One

everything you need to know about js

Uploaded by

memo8800880088
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views13 pages

Js All in One

everything you need to know about js

Uploaded by

memo8800880088
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Comprehensive JavaScript Concepts

Grok

July 3, 2025

Contents
1 Introduction 3

2 Polyfill 3

3 Execution Context 3
3.1 Local and Global Contexts . . . . . . . . . . . . . . . . . . . . . . . . . . 3

4 Call Stack 4

5 Web APIs 4

6 Task Queue 4

7 Starvation in JavaScript 4

8 Coercion 4

9 Truthy and Falsy 4

10 Hoisting 5

11 Temporal Dead Zone (TDZ) 5

12 Scopes 5

13 Closures 5

14 this Keyword 6

15 Prototype Inheritance 6

16 Event Loop and Call Stack 6

17 Optional Chaining (?.) 6

18 Destructuring 6

1
19 Promises 7

20 Nullish Coalescing (??) 7

21 IIFE 7

22 Currying 7

23 Memoization 7

24 Modules (import/export) 8

25 Call by Value 8

26 Call by Reference 8

27 Types 8

28 Object 8

29 Immutability 9

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 Object Literals 10

37 Constructor Function 10

38 Recursive Functions 10

39 Async/Await 10

40 Try/Catch 10

41 Event Delegation 11

42 ES6 Classes 11

43 Arrow Functions 11

44 Template Literals 11

45 Strict Mode 12

2
46 Arrays and Array Methods 12

47 Loops 12

48 JSON 12

49 Event Handling 12

50 Generators 13

51 Conclusion 13

1 Introduction
This document explains key JavaScript concepts, including requested topics and
additional fundamentals. Each section provides a concise overview with exam-
ples, suitable for beginner to intermediate learners.

2 Polyfill
A polyfill implements a feature in browsers lacking support, ensuring compati-
bility.
if (!Array.prototype.includes) {
Array.prototype.includes = function(element) {
return this.indexOf(element) !== -1;
};
}

3 Execution Context
An execution context is the environment where JavaScript code runs, managing
variables and execution.

3.1 Local and Global Contexts


• Global: Default context with global variables/functions.
• Local: Created per function call with its own variables.
let globalVar = ”I’m global”;
function example() {
let localVar = ”I’m local”;
console.log(globalVar, localVar);
}

3
4 Call Stack
The call stack tracks function execution, pushing functions on call and popping
on return.
function first() { second(); }
function second() { console.log(”Called”); }
first();

5 Web APIs
Web APIs (e.g., DOM, setTimeout) are browser features for tasks like timers or
HTTP requests.
setTimeout(() => console.log(”Delayed”), 1000);

6 Task Queue
The task queue holds asynchronous tasks (e.g., setTimeout callbacks) for exe-
cution when 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 con-
tinuous high-priority tasks.

8 Coercion
Coercion is 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.

4
if (”hello”) { console.log(”Truthy”); } // Truthy
if (0) { console.log(”Falsy”); } // Falsy: false, 0, ””, null,
undefined, NaN

10 Hoisting
Hoisting moves variable/function declarations to the top of their scope during
compilation.
console.log(x); // undefined
var x = 5;
foo(); // Works
function foo() { console.log(”Hoisted”); }

11 Temporal Dead Zone (TDZ)


The TDZ is where let and const variables exist but are inaccessible before dec-
laration.
console.log(x); // ReferenceError
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 retaining access to its outer scope’s variables after the
outer function finishes.
function outer() {
let count = 0;
return function inner() { return ++count; };
}

5
let counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2

14 this Keyword
this refers to the object executing the current function, based on call context.
const obj = {
name: ”Test”,
getName: function() { return this.name; }
};
console.log(obj.getName()); // Test

15 Prototype Inheritance
Objects inherit properties/methods from a prototype, linked 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
empty, enabling asynchronous execution.

17 Optional Chaining (?.)


Optional chaining safely accesses properties, returning undefined if 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/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

6
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

20 Nullish Coalescing (??)


?? returns the right operand if the left is null or undefined, otherwise the left.
let value = null ?? ”default”; // default
let defined = 0 ?? 42; // 0

21 IIFE
Immediately Invoked Function Expressions (IIFE) run immediately, often for
scoping.
(function() {
let secret = ”hidden”;
console.log(secret); // hidden
})();

22 Currying
Currying transforms a multi-argument function 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.
function memoize(fn) {
const cache = {};
return x => cache[x] ?? (cache[x] = fn(x));

7
}
let fib = memoize(n => n <= 1 ? n : fib(n - 1) + fib(n - 2));

24 Modules (import/export)
Modules organize code using import and export.
// 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
Primitives are passed by value; parameter changes don’t affect the original.
let x = 10;
function change(y) { y = 20; }
change(x);
console.log(x); // 10

26 Call by Reference
Objects are passed by reference; property changes affect the original.
let obj = { value: 10 };
function change(o) { o.value = 20; }
change(obj);
console.log(obj.value); // 20

27 Types
JavaScript has primitives (number, string, boolean, null, undefined, bigint,
symbol) and objects.

28 Object
Objects are key-value pair collections.
let obj = { key: ”value” };

8
29 Immutability
Immutability prevents object modification, using Object.freeze for shallow
immutability.
let obj = Object.freeze({ x: 1 });
obj.x = 2; // Ignored

30 Deep Cloning
Deep cloning copies nested objects, often using JSON.parse(JSON.stringify()).
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 Object Literals
Shorthand for creating objects.
let x = 1, y = 2;
let obj = { x, y }; // { x: 1, y: 2 }

37 Constructor Function
Functions used with new to create objects.
function Person(name) { this.name = name; }
let p = new Person(”Alice”);

38 Recursive Functions
Functions that call themselves.
function factorial(n) { return n === 0 ? 1 : n * factorial(n - 1); }
console.log(factorial(5)); // 120

39 Async/Await
async/await simplifies promise-based asynchronous code.
async function fetchData() {
let response = await new Promise(resolve => setTimeout(() =>
resolve(”Data”), 1000));
console.log(response); // Data
}
fetchData();

40 Try/Catch
try/catch handles errors gracefully.

10
try {
throw new Error(”Oops”);
} catch (error) {
console.log(error.message); // Oops
}

41 Event Delegation
Event delegation uses a parent element to handle events for children, improving
efficiency.
document.querySelector(”ul”).addEventListener(”click”, e => {
if (e.target.tagName === ”LI”) console.log(e.target.textContent)
;
});

42 ES6 Classes
Classes provide a cleaner syntax for constructor functions and prototypes.
class Person {
constructor(name) { this.name = name; }
greet() { return ‘Hi, ${this.name}‘; }
}
let p = new Person(”Alice”);
console.log(p.greet()); // Hi, Alice

43 Arrow Functions
Arrow functions (=>) offer concise syntax and don’t bind their own this.
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5

44 Template Literals
Template literals use backticks for multi-line strings and interpolation.
let name = ”Alice”;
console.log(‘Hello, ${name}!‘); // Hello, Alice!

11
45 Strict Mode
”use strict” enables stricter parsing and error handling.
”use strict”;
x = 10; // ReferenceError: x is not defined

46 Arrays and Array Methods


Arrays store ordered data, with methods like map, filter, and forEach.
let arr = [1, 2, 3];
let doubled = arr.map(x => x * 2); // [2, 4, 6]
let evens = arr.filter(x => x % 2 === 0); // [2]
arr.forEach(x => console.log(x)); // 1, 2, 3

47 Loops
Loops repeat code execution, including for, while, and for...of.
for (let i = 0; i < 3; i++) { console.log(i); } // 0, 1, 2
let j = 0;
while (j < 3) { console.log(j++); } // 0, 1, 2
for (let x of [1, 2, 3]) { console.log(x); } // 1, 2, 3

48 JSON
JSON (JavaScript Object Notation) is used for data interchange.
let obj = { name: ”Alice” };
let json = JSON.stringify(obj); // ’{”name”:”Alice”}’
let parsed = JSON.parse(json); // { name: ”Alice” }

49 Event Handling
Event listeners handle user interactions like clicks or keypresses.
document.querySelector(”button”).addEventListener(”click”, () => {
console.log(”Clicked”);
});

12
50 Generators
Generators are functions that pause and resume, yielding values one at a time.
function* generator() {
yield 1;
yield 2;
}
let gen = generator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

51 Conclusion
This document covers a comprehensive set of JavaScript concepts. Practice with
projects and refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript
for deeper insights.

13

You might also like