[Go to site: main page, start]

0% found this document useful (0 votes)
8 views32 pages

JavaScript Study Material

The document is a comprehensive study material for JavaScript, covering topics from basics to advanced concepts. It includes sections on variables, data types, functions, arrays, objects, scope, closures, and more, along with practical examples and explanations. Additionally, it provides insights into JavaScript error types and interview questions, making it a valuable resource for learners and developers.

Uploaded by

Rudy
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)
8 views32 pages

JavaScript Study Material

The document is a comprehensive study material for JavaScript, covering topics from basics to advanced concepts. It includes sections on variables, data types, functions, arrays, objects, scope, closures, and more, along with practical examples and explanations. Additionally, it provides insights into JavaScript error types and interview questions, making it a valuable resource for learners and developers.

Uploaded by

Rudy
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

Complete JavaScript Study Material

Table of Contents
1. JavaScript Basics
2. Variables & Data Types
3. Functions Deep Dive
4. Arrays & Objects
5. Scope & Closures
6. this Keyword & Binding
7. OOP in JavaScript
8. DOM Manipulation
9. Events & Event Propagation
10. Asynchronous JavaScript
11. HTTP, APIs & Fetch
12. Promises & Async/Await
13. ES6+ Features
14. Browser APIs
15. Git Commands
16. Interview Questions

1. JavaScript Basics
1.1 Scripting Language vs Programming Language

Aspect Scripting Language Programming Language

Execution Interpreted line-by-line Compiled to machine code


Speed Slower (runtime interpretation) Faster (pre-compiled)
Type Usually dynamically typed Usually statically typed
Use Case Automation, web, glue code System software, applications
Examples JavaScript, Python, Ruby C, C++, Java, Rust

JavaScript is a scripting language — interpreted by the browser’s engine (V8 in Chrome). Modern
JS uses Just-In-Time (JIT) compilation for performance.

1.2 Chrome DevTools

Open with F12 or Ctrl+Shift+I (Windows) / Cmd+Option+I (Mac).

Tab Purpose

Elements Inspect and edit HTML/CSS live


Console Run JS, view logs, debug
Sources Set breakpoints, step through code
Network Monitor HTTP requests/responses

Generated by [Link]
Table 2 – continued
Tab Purpose

Application View LocalStorage, Cookies, SessionStorage


Performance Profile runtime performance

Console shortcuts:
[Link]("Debug message");
[Link]([{name: "A", age: 20}, {name: "B", age: 25}]);
[Link]("Error!");
[Link]("Warning!");
[Link]([Link]); // Object tree view

1.3 Type Coercion

JavaScript automatically converts types when operators expect different types.

// String coercion
"5" + 3; // "53" (number → string)
"5" - 3; // 2 (string → number)

// Boolean coercion
if ("hello") { } // true (non-empty string is truthy)
if (0) { } // false (0 is falsy)
if ([]) { } // true (empty array is truthy!)

// Explicit conversion
Number("42"); // 42
String(42); // "42"
Boolean(1); // true
parseInt("10px"); // 10
parseFloat("3.14");// 3.14

// Falsy values: false, 0, "" (empty string), null, undefined, NaN


// Everything else is truthy

Reference: [Link]/type-conversions

1.4 Arithmetic & Short-Circuiting

// Short-circuit evaluation
let name = userInput || "Guest"; // Returns first truthy value
let value = userInput && [Link](); // Returns first falsy value
let count = userCount ?? 0; // Nullish coalescing (only null/undefined)

// Logical operators
true && false; // false
true || false; // true
!true; // false

Generated by [Link]
// Ternary operator
let status = age >= 18 ? "Adult" : "Minor";

2. Variables & Data Types


2.1 var, let, const

Feature var let const

Scope Function scope Block scope {} Block scope {}


Hoisting Hoisted (initialized Hoisted (not Hoisted (not initialized)
undefined) initialized)
Re-declaration Allowed Not allowed Not allowed
Re-assignment Allowed Allowed Not allowed
Temporal Dead Zone No Yes Yes

// var - function scoped


function test() {
if (true) {
var x = 10; // Accessible outside the if block
}
[Link](x); // 10
}

// let - block scoped


function test() {
if (true) {
let y = 10;
}
[Link](y); // ReferenceError: y is not defined
}

// const - must initialize, cannot reassign


const PI = 3.14159;
PI = 3; // TypeError: Assignment to constant variable

// BUT: const objects/arrays can be mutated


const person = { name: "John" };
[Link] = "Jane"; // Works!
person = {}; // TypeError

// Temporal Dead Zone (TDZ)


[Link](a); // undefined (var is hoisted)
var a = 5;

[Link](b); // ReferenceError (TDZ - let not initialized)


let b = 5;

Generated by [Link]
2.2 Data Types

Primitive Types (stored in stack, passed by value):

let str = "Hello"; // String


let num = 42; // Number (includes integers and floats)
let big = 9007199254740992n; // BigInt (for numbers >= 2^53)
let bool = true; // Boolean
let undef = undefined; // Undefined (variable declared but not assigned)
let nul = null; // Null (intentional absence of value)
let sym = Symbol("id"); // Symbol (unique identifier)

Special Number Values:

Infinity; // Positive infinity


-Infinity; // Negative infinity
NaN; // Not a Number (result of invalid math)
3e5; // 3 × 10^5 = 300000 (scientific notation)

Non-Primitive Type (stored in heap, passed by reference):

let obj = { name: "John" }; // Object


let arr = [1, 2, 3]; // Array (type is also "object")
let fn = function() {}; // Function (type is "function")

typeof 1; // "number"
typeof typeof 1; // "string" (typeof returns string "number")
typeof null; // "object" (JavaScript bug, never fixed for compatibility)
typeof []; // "object"
typeof function(){} // "function"

3. Functions Deep Dive


3.1 Function Basics
// Function declaration (hoisted)
function greet(name) {
return "Hello, " + name;
}

// No return type specified


function noReturn() {
[Link]("No return");
// Returns undefined implicitly
}

// Missing parameter → undefined


function missingParam(a, b) {
[Link](a, b); // 5, undefined
}
missingParam(5);

Generated by [Link]
// No parameter type checking
function add(a, b) {
return a + b; // Could be numbers, strings, anything
}

3.2 Function Hoisting

// Function declarations are hoisted (moved to top)


sayHello(); // Works!
function sayHello() {
[Link]("Hello!");
}

// Function expressions are NOT hoisted


sayGoodbye(); // TypeError: sayGoodbye is not a function
var sayGoodbye = function() {
[Link]("Goodbye!");
};

3.3 Function Expression

// Anonymous function expression


const multiply = function(a, b) {
return a * b;
};

// Named function expression (useful for recursion)


const factorial = function fact(n) {
if (n <= 1) return 1;
return n * fact(n - 1); // Can reference itself internally
};

// Arrow function (ES6)


const divide = (a, b) => a / b;
const square = x => x * x;
const getObj = () => ({ a: 1 }); // Wrap in () to return object!

3.4 Function as Parameter (Higher-Order Function)

function operate(a, b, operation) {


return operation(a, b);
}

const add = (x, y) => x + y;


const result = operate(5, 3, add); // 8

// Nested functions
function outer() {
let count = 0;

Generated by [Link]
function inner() {
count++;
return count;
}
return inner;
}
const counter = outer();
[Link](counter()); // 1
[Link](counter()); // 2

3.5 Window Prompt, Alert, Confirm

// Alert - shows message


alert("Hello!");

// Prompt - asks for input


let name = prompt("Enter your name:", "Guest");

// Confirm - yes/no dialog


let isSure = confirm("Are you sure?"); // Returns true or false

3.6 JavaScript Error Types

Error Type Cause

ReferenceError Variable/function doesn’t exist


TypeError Value is not expected type
SyntaxError Invalid syntax
RangeError Number out of range
URIError Invalid URI encoding
EvalError Error in eval() function

try {
let x = undefinedVariable; // ReferenceError
} catch (error) {
[Link]([Link]); // "ReferenceError"
[Link]([Link]); // "undefinedVariable is not defined"
} finally {
[Link]("Always runs");
}

// Unhandled rejection (Promises)


[Link]("unhandledrejection", event => {
[Link]("Unhandled promise rejection:", [Link]);
});

Reference: MDN JavaScript Errors

Generated by [Link]
4. Arrays & Objects
4.1 Arrays in JavaScript

let arr = [1, 2, 3];


arr[10] = 99; // Can assign to any index
[Link](arr); // [1, 2, 3, empty × 7, 99]
[Link]([Link]); // 11 (max index + 1)
[Link](arr[5]); // undefined (sparse array)

// Array methods
[Link](4); // Add to end → [1,2,3,4]
[Link](); // Remove from end → [1,2,3]
[Link](); // Remove from start → [2,3]
[Link](0); // Add to start → [0,2,3]

// Splice - remove/replace/add at index


let nums = [1, 2, 3, 4, 5];
[Link](1, 2); // From index 1, remove 2 items → [1, 4, 5]
[Link](1, 0, "a"); // From index 1, remove 0, insert "a" → [1, "a", 4, 5]

// Slice - extract portion (non-mutating)


let sliced = [1, 2, 3, 4, 5].slice(1, 4); // [2, 3, 4] (index 1 to 3)

// Other useful methods


[Link](2); // true
[Link](2); // 1
[Link]("-"); // "1-2-3"
[Link](); // Mutates original!
[Link](); // Sorts as strings by default!
[Link]((a, b) => a - b); // Numeric sort

4.2 Iterating Over Arrays

const fruits = ["apple", "banana", "cherry"];

// forEach - executes for each item, returns undefined


[Link]((fruit, index) => {
[Link](index, fruit);
});

// map - transforms each item, returns NEW array


const upperFruits = [Link](fruit => [Link]());
// ["APPLE", "BANANA", "CHERRY"]

// filter - returns items that pass test


const longFruits = [Link](fruit => [Link] > 5);
// ["banana", "cherry"]

// find - returns first matching item


const found = [Link](fruit => [Link]("b"));
// "banana"

Generated by [Link]
// for...of (ES6) - iterates values
for (const fruit of fruits) {
[Link](fruit);
}

// for...in - iterates INDICES (not recommended for arrays)


for (const index in fruits) {
[Link](index); // "0", "1", "2"
}

forEach vs map:

• forEach: Side effects only, returns undefined, cannot break early

• map: Returns new array, transforms data, chainable

4.3 Objects in JavaScript

// Object literal
const person = {
name: "John",
age: 30,
"favorite color": "blue" // Key with space needs quotes
};

// Access properties
[Link]; // "John"
person["name"]; // "John"
person["favorite color"]; // "blue" (bracket notation for invalid identifiers)

// Add/Update/Delete properties
[Link] = "New York"; // Add
[Link] = 31; // Update
delete [Link]; // Delete

// Check property
"name" in person; // true
[Link]("name"); // true (own property, not inherited)

4.4 Cloning Objects

const original = { a: 1, b: { c: 2 } };

// Shallow clone (spread)


const clone1 = { ...original };

// Shallow clone ([Link])


const clone2 = [Link]({}, original);

// Deep clone (JSON method - loses functions, dates, undefined)


const deepClone = [Link]([Link](original));

Generated by [Link]
// Deep clone (modern method)
const deepClone2 = structuredClone(original);

// Deep clone (comprehensive)


const clone3 = [Link](
[Link](original),
[Link](original)
);

// WARNING: Spread and assign are SHALLOW


clone1.b.c = 99;
[Link](original.b.c); // 99! (nested object shared)

4.5 Iterating Over Objects

const user = { name: "John", age: 30, city: "NYC" };

// [Link] - returns array of keys


[Link](user); // ["name", "age", "city"]

// [Link] - same as keys for plain objects


[Link](user); // ["name", "age", "city"]

// [Link] - returns array of values


[Link](user); // ["John", 30, "NYC"]

// [Link] - returns [key, value] pairs


[Link](user); // [["name", "John"], ["age", 30], ["city", "NYC"]]

// for...in - iterates over all enumerable properties (including prototype chain)


for (const key in user) {
if ([Link](key)) { // Check to avoid inherited properties
[Link](key, user[key]);
}
}

4.6 Array is an Object

typeof []; // "object"


[Link]([]); // true
[Link]({}); // false

// Array length is the max integral index + 1


let arr = [];
arr[100] = "x";
[Link]([Link]); // 101

Generated by [Link]
4.7 Set and Map

// Set - unique values only


const uniqueNums = new Set([1, 2, 2, 3, 3, 3]);
[Link]([...uniqueNums]); // [1, 2, 3]
[Link](4);
[Link](2); // true
[Link](2);

// Map - key-value pairs with any type of key


const map = new Map();
[Link]("name", "John");
[Link](42, "number key");
[Link]({ a: 1 }, "object key");
[Link]([Link]("name")); // "John"
[Link]("name"); // true
[Link]("name");

// WeakMap - keys must be objects, garbage collectible


const weakMap = new WeakMap();
let obj = {};
[Link](obj, "data");
obj = null; // Entry automatically removed by garbage collector

5. Scope & Closures


5.1 Types of Scope

// Global scope
let globalVar = "I'm global";

function outer() {
// Function/Lexical scope
let outerVar = "I'm in outer";

function inner() {
// Can access outer and global
[Link](outerVar); //
[Link](globalVar); //
let innerVar = "I'm in inner";
}

// [Link](innerVar); // ReferenceError
inner();
}

// Block scope (with let/const)


if (true) {
let blockVar = "I'm block scoped";
const blockConst = "Me too";

Generated by [Link]
}
// [Link](blockVar); // ReferenceError

// var ignores block scope!


if (true) {
var notBlockScoped = "I leak out!";
}
[Link](notBlockScoped); // Works (function scoped)

5.2 Avoiding Global Variables

// IIFE (Immediately Invoked Function Expression)


(function() {
let privateVar = "I'm private";
[Link](privateVar);
})();
// privateVar is not accessible outside

// IIFE variations
(function() { /* code */ }());
(() => { /* code */ })();
(async function() { /* code */ })();

// Module pattern (modern alternative)


const myModule = (function() {
let privateVar = 0;
return {
increment: () => ++privateVar,
get: () => privateVar
};
})();
[Link]();

5.3 Closures

A closure is a function + its lexical environment (variables it was created with).

function makeCounter() {
let count = 0; // Enclosed variable

return function() {
return ++count; // Remembers count from outer scope
};
}

const counter1 = makeCounter();


const counter2 = makeCounter();

[Link](counter1()); // 1
[Link](counter1()); // 2
[Link](counter2()); // 1 (separate closure!)

Generated by [Link]
// Closures with let in loops (classic interview question)
for (var i = 0; i < 3; i++) {
setTimeout(() => [Link](i), 100); // 3, 3, 3 (var is function scoped)
}

for (let i = 0; i < 3; i++) {


setTimeout(() => [Link](i), 100); // 0, 1, 2 (let is block scoped, new binding each iteration)
}

Closure preserves scope: Even after the outer function finishes executing, the inner function retains
access to the outer function’s variables.

6. this Keyword & Binding


6.1 How this Works
// 1. Global context → window (browser) or global (Node)
[Link](this); // window

// 2. Method call → object that owns the method


const user = {
name: "John",
greet() {
return "Hello, " + [Link];
}
};
[Link](); // "Hello, John" (this = user)

// 3. Function call → undefined in strict mode, window otherwise


function showThis() {
[Link](this);
}
showThis(); // undefined (strict) or window (non-strict)

// 4. Constructor call → new object


function Person(name) {
[Link] = name; // this = newly created object
}
const p = new Person("John");

6.2 Arrow Functions & this

Arrow functions do NOT have their own this. They inherit this from the enclosing scope.

const obj = {
name: "John",
regularFunc: function() {
[Link]([Link]); // "John"
},

Generated by [Link]
arrowFunc: () => {
[Link]([Link]); // undefined (inherits this from outer scope)
}
};

// Arrow functions are great for callbacks


const timer = {
count: 0,
start() {
setInterval(() => {
[Link]++; // 'this' refers to timer object!
[Link]([Link]);
}, 1000);
}
};

6.3 call, apply, bind

function greet(greeting, punctuation) {


return greeting + ", " + [Link] + punctuation;
}

const person = { name: "John" };

// call - invoke with specific this, args as comma-separated


[Link](person, "Hello", "!"); // "Hello, John!"

// apply - invoke with specific this, args as array


[Link](person, ["Hi", "."]); // "Hi, John."

// bind - returns new function with fixed this


const boundGreet = [Link](person, "Hey");
boundGreet("?"); // "Hey, John?"

// Changing function's this by making it a property


const obj = { name: "Jane" };
[Link] = greet;
[Link]("Hello", "!"); // "Hello, Jane!" (this = obj)

Reference: MDN this keyword

7. OOP in JavaScript
7.1 Constructor Functions
function Person(name, age) {
// 'new' creates a new object and binds 'this' to it
[Link] = name;
[Link] = age;
}

Generated by [Link]
// Prototype method (shared among all instances)
[Link] = function() {
return "Hi, I'm " + [Link];
};

const john = new Person("John", 30);


const jane = new Person("Jane", 25);

[Link]([Link]()); // "Hi, I'm John"


[Link]([Link] === [Link]); // true (same function!)

7.2 Prototype Chain

// Every object has a prototype


john.__proto__ === [Link]; // true (dunder proto)
[Link](john) === [Link]; // true (modern way)

// Prototype chain lookup


[Link](); // Found on [Link] ([Link] → [Link])

// Check property source


[Link]("name"); // true (own property)
[Link]("greet"); // false (inherited from prototype)

// Add to prototype at runtime


[Link] = function() {
return "Bye from " + [Link];
};
[Link](); // Works! All instances get the new method

7.3 ES6 Classes


class Animal {
constructor(name) {
[Link] = name;
}

speak() {
return [Link] + " makes a sound";
}

// Static method (called on class, not instance)


static isAnimal(obj) {
return obj instanceof Animal;
}
}

class Dog extends Animal {


constructor(name, breed) {
super(name); // Call parent constructor

Generated by [Link]
[Link] = breed;
}

speak() {
return [Link]() + " and barks!"; // Call parent method
}
}

const dog = new Dog("Rex", "German Shepherd");


[Link](); // "Rex makes a sound and barks!"

// Class is NOT hoisted!


// new Animal(); // ReferenceError if class declared below

// Cannot call class without new


// Animal("test"); // TypeError

7.4 Class vs Function

Feature Function Constructor ES6 Class

Hoisting Hoisted Not hoisted


Call without new Creates global pollution TypeError
Syntax Prototype-based Syntactic sugar over prototypes
typeof "function" "function"

8. DOM Manipulation
8.1 Accessing DOM Elements

// By ID (fastest)
const header = [Link]("header");

// By tag name (returns HTMLCollection - live)


const paragraphs = [Link]("p");

// By class name (returns HTMLCollection - live)


const buttons = [Link]("btn");

// Query selector (first match)


const firstBtn = [Link](".btn");
const navLink = [Link]("nav [Link]");

// Query selector all (returns NodeList - static)


const allBtns = [Link](".btn");
[Link](btn => [Link] = "red");

Differences:

• HTMLCollection is live (updates automatically), NodeList is static (snapshot)

Generated by [Link]
• HTMLCollection has length and index access, NodeList has forEach()

8.2 DOM Properties

// Document properties
[Link]; // <html> element
[Link]; // <head> element
[Link]; // <body> element
[Link]; // Page title

// Window properties
[Link]; // Viewport width
[Link]; // Viewport height
[Link]; // Current URL
[Link](); // Refresh page
[Link]; // Screen width
[Link]; // Browser identity string

// Media queries in JS
const isMobile = [Link]("(max-width: 768px)");
[Link]; // true or false
[Link]("change", (e) => {
[Link]([Link] ? "Mobile" : "Desktop");
});

8.3 Modifying DOM

const div = [Link]("div");


[Link] = "container";
[Link] = "main";
[Link] = "Hello"; // Plain text (safer)
[Link] = "<strong>Hello</strong>"; // Parses HTML (XSS risk!)

// Attributes
[Link]("data-id", "123");
[Link]("data-id"); // "123"
[Link]("data-id");

// Classes
[Link]("active");
[Link]("hidden");
[Link]("visible");
[Link]("active"); // true

// Styles
[Link] = "red";
[Link] = "color: blue; font-size: 16px;";

// Insert into DOM


[Link](div); // Add as last child
[Link](div); // Add as first child

Generated by [Link]
[Link](div, sibling); // Insert before specific element
[Link](div); // Remove element

9. Events & Event Propagation


9.1 Event Handling

// Inline (not recommended)


// <button >

// addEventListener (recommended)
const btn = [Link]("#myBtn");

[Link]("click", function(event) {
[Link]("Clicked!");
[Link]([Link]); // Element that triggered event
[Link]([Link]); // Element listener is attached to
[Link]([Link]); // "click"
});

// Remove listener (must use named function)


function handler() { [Link]("Once"); }
[Link]("click", handler);
[Link]("click", handler);

// Multiple events on same element


[Link]("mouseover", () => [Link] = "blue");
[Link]("mouseout", () => [Link] = "");

9.2 Mouse & Keyboard Events

// Mouse events
[Link]("mouseover", e => [Link]("Mouse entered"));
[Link]("mouseout", e => [Link]("Mouse left"));
[Link]("mousemove", e => {
[Link]([Link], [Link]); // Mouse position
});

// Keyboard events
[Link]("keydown", e => {
[Link]([Link]); // Key name ("Enter", "a", "ArrowUp")
[Link]([Link]); // Deprecated, use key instead
[Link]([Link]); // Physical key code ("KeyA", "Space")
if ([Link] === "Enter") {
[Link]("Enter pressed!");
}
});

// keypress - only detects printable characters (deprecated, use keydown)

Generated by [Link]
[Link]("keypress", e => {
[Link]([Link]); // Letters, numbers only
});

9.3 Event Propagation

// Event phases: CAPTURE (root → target) → TARGET → BUBBLE (target → root)

// Bubbling (default) - event travels UP from target to ancestors


[Link]("click", () => [Link]("outer"));
[Link]("click", () => [Link]("inner"));
[Link]("click", () => [Link]("button"));
// Click button → "button" → "inner" → "outer"

// Capturing - event travels DOWN from ancestors to target


[Link]("click", () => [Link]("outer capture"), true);
// Click button → "outer capture" → "button" → "inner" → "outer"

// Stop propagation
[Link]("click", (e) => {
[Link](); // Stop bubbling up
[Link]("button only");
});

// Prevent default behavior


[Link]("submit", (e) => {
[Link](); // Don't submit the form
});

Reference: [Link]/bubbling-and-capturing

10. Asynchronous JavaScript


10.1 JavaScript is Single-Threaded

JavaScript runs on a single thread with one call stack. Asynchronous operations are handled by the
browser/Node APIs and placed in queues.

// Synchronous - blocks execution


[Link]("1");
[Link]("2");
[Link]("3");
// Output: 1, 2, 3

// Asynchronous - non-blocking
[Link]("1");
setTimeout(() => [Link]("2"), 0); // Goes to queue
[Link]("3");
// Output: 1, 3, 2

Generated by [Link]
10.2 Timing Functions

// setTimeout - executes once after delay


const timeoutId = setTimeout(() => {
[Link]("After 2 seconds");
}, 2000);
clearTimeout(timeoutId); // Cancel

// setInterval - executes repeatedly


const intervalId = setInterval(() => {
[Link]("Every 1 second");
}, 1000);
clearInterval(intervalId); // Stop

// setImmediate ([Link]) - executes after I/O events


// setImmediate(() => [Link]("Immediate"));

10.3 Callback Functions

A function passed as an argument to another function, executed later.

function fetchData(callback) {
setTimeout(() => {
const data = { id: 1, name: "John" };
callback(data);
}, 1000);
}

fetchData((data) => {
[Link](data);
});

// Callback Hell (Pyramid of Doom)


getData((data) => {
processData(data, (processed) => {
saveData(processed, (saved) => {
notifyUser(saved, (notified) => {
// Deep nesting - hard to read and maintain
});
});
});
});

10.4 JavaScript Event Loop

┌──────────────┐ ┌─────────────┐ ┌─────────────┐


│ Call Stack │ │ Web APIs │ │ Queues │
│ ( executes │ ←── │ (setTimeout,│ ←── │ (Callback │
│ code ) │ │ fetch, │ │ Queue, │
│ │ │ DOM, etc)│ │ Microtask │
│ │ │ │ │ Queue) │

Generated by [Link]
└──────────────┘ └─────────────┘ └─────────────┘
↑ │
└────────────────────────────────────────┘
(Event Loop)

Execution Order:

1. Execute all synchronous code in call stack

2. Execute all microtasks (Promises, queueMicrotask)

3. Execute one macrotask (setTimeout, setInterval, I/O)

4. Repeat

[Link]("1"); // Sync

setTimeout(() => [Link]("2"), 0); // Macrotask

[Link]().then(() => [Link]("3")); // Microtask

[Link]("4"); // Sync

// Output: 1, 4, 3, 2
// (Sync first, then microtasks, then macrotasks)

11. HTTP, APIs & Fetch


11.1 Client-Server Architecture
┌─────────┐ HTTP Request ┌─────────┐
│ Client │ ─────────────→ │ Server │
│ (Browser)│ │ (API) │
│ │ ←───────────── │ │
└─────────┘ HTTP Response └─────────┘

HTTP is stateless — each request is independent, server doesn’t remember previous requests.

11.2 HTTP Methods (REST API)

Method Action Example

GET Fetch data GET /users —get all users


POST Create data POST /users —create new user
PUT Update entire resource PUT /users/1 —replace user 1
PATCH Partial update PATCH /users/1 —update name
only
DELETE Remove data DELETE /users/1 —delete user 1

Reference: Red Hat REST API Guide

Generated by [Link]
11.3 Fetch API
// GET request
fetch("[Link]
.then(response => {
if (![Link]) {
throw new Error("HTTP " + [Link]);
}
return [Link](); // Parse JSON
})
.then(data => [Link](data))
.catch(error => [Link]("Error:", error));

// POST request
fetch("[Link] {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer token123"
},
body: [Link]({ name: "John", email: "john@[Link]" })
})
.then(response => [Link]())
.then(data => [Link](data));

11.4 HTTP Response Codes

Code Meaning

200 OK - Success
201 Created
204 No Content
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
500 Internal Server Error
502 Bad Gateway
503 Service Unavailable

11.5 JSON
// JavaScript Object
const obj = { name: "John", age: 30 };

// Convert to JSON string


const jsonString = [Link](obj);
// '{"name":"John","age":30}'

// Convert JSON string to object

Generated by [Link]
const parsed = [Link](jsonString);
// { name: "John", age: 30 }

// [Link] options
[Link](obj, null, 2); // Pretty print with 2-space indentation

11.6 CORS (Cross-Origin Resource Sharing)

CORS errors occur when a web page requests resources from a different domain without proper server
headers.
// Server must send headers:
// Access-Control-Allow-Origin: *
// Access-Control-Allow-Methods: GET, POST
// Access-Control-Allow-Headers: Content-Type

// In fetch, credentials for cookies:


fetch(url, { credentials: "include" });

12. Promises & Async/Await


12.1 Promise States
new Promise(executor)


┌───────┐
│PENDING│
└──┬────┘

┌──┴──────────┐
↓ ↓
┌───────┐ ┌────────┐
│FULFILLED│ │REJECTED│
│(resolve)│ │(reject) │
└────┬────┘ └────┬───┘
│ │
↓ ↓
.then() .catch()

const promise = new Promise((resolve, reject) => {


setTimeout(() => {
const success = true;
if (success) {
resolve("Data loaded!");
} else {
reject("Error loading data");
}
}, 1000);
});

Generated by [Link]
promise
.then(result => [Link](result)) // "Data loaded!"
.catch(error => [Link](error)) // If rejected
.finally(() => [Link]("Done")); // Always runs

12.2 Promise Methods


// [Link] - waits for ALL, fails if ANY fails
[Link]([fetch(url1), fetch(url2), fetch(url3)])
.then(results => [Link](results));

// [Link] - returns first settled (success or failure)


[Link]([fetch(url1), fetch(url2)])
.then(result => [Link]("First:", result));

// [Link] - waits for ALL, never fails


[Link]([fetch(url1), fetch(url2)])
.then(results => [Link](r => [Link]([Link])));

// [Link] - returns first fulfilled, fails if ALL reject


[Link]([fetch(url1), fetch(url2)])
.then(result => [Link](result));

// [Link] / [Link]
[Link](42); // Instantly resolved
[Link]("err"); // Instantly rejected

12.3 Async/Await

Syntactic sugar over Promises — makes async code look synchronous.

async function getUserData(userId) {


try {
const response = await fetch(`/api/users/${userId}`);
if (![Link]) throw new Error("Failed to fetch");

const user = await [Link]();


const posts = await fetch(`/api/users/${userId}/posts`);
const postsData = await [Link]();

return { user, posts: postsData };


} catch (error) {
[Link]("Error:", error);
throw error; // Re-throw for caller to handle
} finally {
[Link]("Request completed");
}
}

// Usage

Generated by [Link]
getUserData(1)
.then(data => [Link](data))
.catch(err => [Link](err));

// Or in another async function


(async () => {
const data = await getUserData(1);
[Link](data);
})();

13. ES6+ Features


13.1 Constants & Block Scoping

const PI = 3.14159; // Cannot reassign


let count = 0; // Block scoped, can reassign

// Block scoping with {}


{
let x = 10;
const y = 20;
}
// x and y are not accessible here

// Temporal Dead Zone


[Link](a); // ReferenceError
let a = 5;

// This won't work!


if (true) let a = 1; // SyntaxError: Lexical declaration not in statement
if (true) { let a = 1; } // Works with block

13.2 Template Literals & Destructuring

// Template literals
const name = "John";
const message = `Hello, ${name}! Today is ${new Date().toDateString()}`;

// Multi-line strings
const html = `
<div>
<h1>Title</h1>
</div>
`;

// Destructuring arrays
const [first, second, ...rest] = [1, 2, 3, 4, 5];
// first=1, second=2, rest=[3,4,5]

Generated by [Link]
// Destructuring objects
const { name: userName, age = 25 } = { name: "John" };
// userName="John", age=25 (default value)

// Nested destructuring
const { address: { city } } = { address: { city: "NYC" } };

// Function parameter destructuring


function greet({ name, age }) {
return `Hi ${name}, you are ${age}`;
}

13.3 Spread & Rest Operators

// Spread (expands iterables)


const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }

// Rest (collects remaining)


function sum(...numbers) {
return [Link]((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // 10

const [first, ...others] = [1, 2, 3, 4];


// first=1, others=[2,3,4]

13.4 Other ES6+ Features

// Default parameters
function greet(name = "Guest") {
return `Hello, ${name}`;
}

// Object shorthand
const name = "John";
const age = 30;
const person = { name, age, greet() { return "Hi"; } };
// Same as: { name: name, age: age, greet: function() { ... } }

// Computed property names


const key = "name";
const obj = { [key]: "John", [key + "2"]: "Jane" };

// Optional chaining (ES2020)


const city = user?.address?.city; // undefined instead of error

// Nullish coalescing (ES2020)

Generated by [Link]
const value = userCount ?? 0; // Only for null/undefined, not 0 or ""

// Dynamic import (ES2020)


const module = await import("./[Link]");

// BigInt
const huge = 9007199254740993n;
const alsoHuge = BigInt(9007199254740993);

Reference: ES6 Features

14. Browser APIs


14.1 LocalStorage & SessionStorage

// localStorage - persists after browser close


[Link]("username", "John");
const user = [Link]("username");
[Link]("username");
[Link](); // Remove all

// sessionStorage - clears when tab closes


[Link]("token", "abc123");

// Storage events (cross-tab communication)


[Link]("storage", (e) => {
[Link]([Link], [Link], [Link]);
});

14.2 Cookies
// Set cookie
[Link] = "username=John; expires=Fri, 31 Dec 2026 23:59:59 GMT; path=/; Secure;
↪ SameSite=Strict";

// Read all cookies


[Link]([Link]);

15. Git Commands


# Why Git? Track changes, collaborate, revert mistakes

# Install: [Link]

# Initialize repository
git init

# Check status

Generated by [Link]
git status

# Stage files
git add [Link] # Stage specific file
git add . # Stage all changes

# Commit
git commit -m "Descriptive message"

# View history
git log --oneline

# Branches
git branch feature-name # Create branch
git checkout feature-name # Switch branch
git checkout -b feature-name # Create and switch
git merge feature-name # Merge into current branch

# Remote
git remote add origin <url>
git push -u origin main
git pull origin main

Reference: Atlassian Git Cheat Sheet

16. Interview Questions


JavaScript — Basic

Q1. What is typeof typeof 1?

typeof 1; // "number"
typeof "number"; // "string"
// Answer: "string"

Q2. Difference between var, let, const?

• var: Function scoped, hoisted, can re-declare

• let: Block scoped, hoisted but TDZ, cannot re-declare

• const: Block scoped, must initialize, cannot reassign

Q3. forEach() vs map() vs filter() vs find()

• forEach: Iterates, no return, side effects

• map: Transforms, returns new array

• filter: Returns items passing test

• find: Returns first matching item

Q4. slice() vs splice()

Generated by [Link]
• slice(start, end): Non-mutating, extracts portion

• splice(start, deleteCount, ...items): Mutating, removes/replaces/adds

Q5. What is the Window Object Model (WOM)? The global object in browsers. Contains
document, location, navigator, screen, history, setTimeout, etc.

Q6. Event Capturing vs Event Bubbling

• Capturing: Event travels from root to target (top-down)

• Bubbling: Event travels from target to root (bottom-up)

• Default is bubbling. Use 3rd argument true in addEventListener for capturing.

JavaScript — Intermediate

Q1. typeof null?

typeof null; // "object" (JavaScript bug from first implementation, kept for compatibility)

Q2. What does [Link]() do? Copies enumerable own properties from source objects to target
object (shallow copy).

Q3. ({ a } = b) — Destructuring assignment Extracts property a from object b and assigns to


variable a.

Q4. JavaScript Error Types

• ReferenceError: Variable not defined

• TypeError: Wrong type operation

• SyntaxError: Invalid syntax

• RangeError: Number out of range

• URIError: Invalid URI

Q5. Callback Hell & Event Loop Callback hell = deeply nested callbacks. Solved with Promises/
async-await. Event loop handles async execution order.

Q6. Higher-Order Function vs Callback Function

• HOF: Function that takes/returns a function (map, filter)

• Callback: Function passed as argument to another function

JavaScript — Advanced

Q1. What is hoisting? JavaScript moves declarations to the top of their scope during compilation.
var and function declarations are hoisted; let and const are hoisted but in Temporal Dead Zone.

Q2. What is BigInt? Data type for integers beyond Number.MAX_SAFE_INTEGER (2^53 - 1).

Q3. Special Number Values

• Infinity, -Infinity: Result of dividing by zero

Generated by [Link]
• NaN: Not a Number (invalid math operation)

• 3e5: Scientific notation (3 × 10^5 = 300000)

Q4. What is e in numbers? Scientific notation: 3e5 = 3 × 10^5 = 300000

Q5. What is the V8 Engine? Google’s open-source JS engine used in Chrome and [Link]. Compiles
JS to machine code using JIT compilation.

CSS Interview Questions

Q1. Box Model — Why isn’t outline included? Outline is drawn outside the border and does not
affect layout (doesn’t take up space or push elements).

Q2. Flex vs Grid

• Flexbox: One-dimensional (row OR column), content-first

• Grid: Two-dimensional (rows AND columns), layout-first

Q3. box-sizing: border-box vs content-box

• content-box: Width/height applies to content only (padding and border add to total)

• border-box: Width/height includes padding and border (content shrinks to fit)

Q4. visibility: hidden vs display: none vs opacity: 0

• display: none: Removed from layout, no space reserved

• visibility: hidden: Space reserved, not visible, not interactive

• opacity: 0: Space reserved, not visible, still interactive (clickable)

Q5. Pseudo-classes vs Pseudo-elements

• Pseudo-classes (:): Select based on state (:hover, :nth-child)

• Pseudo-elements (::): Select part of element (::before, ::after, ::first-line)

Q6. % vs vh/vw

• %: Relative to parent element’s dimension

• vh/vw: Relative to viewport dimension (1vh = 1% of viewport height)

Q7. @font-face Allows loading custom fonts: @font-face { font-family: "MyFont"; src:
url("font.woff2"); }

Q8. @keyframes Defines animation stages: @keyframes slide { from { left: 0; } to { left: 100px; }
}

Q9. min(), max(), minmax(), clamp()

• min(50%, 500px): Smaller of the two values

• max(50%, 500px): Larger of the two values

• minmax(200px, 1fr): Grid track between min and max

• clamp(1rem, 2.5vw, 2rem): Value between min and max, preferred in middle

Generated by [Link]
Q10. backface-visibility Determines if back of element is visible during 3D transforms. hidden for flip
card effects.

Q11. white-space Controls text wrapping: normal, nowrap, pre, pre-wrap, pre-line

Q12. perspective Sets distance between viewer and z=0 plane for 3D transforms. Applied to parent for
children.

Q13. box-decoration-break Controls rendering of element fragments across lines (slice or clone).

HTML Interview Questions

Q1. Inline vs Block Elements

• Block: Takes full width, starts new line (div, p, h1-h6)

• Inline: Takes needed width, flows with text (span, a, strong)

Q2. id vs class

• id: Unique per page, one element, high specificity

• class: Reusable, multiple elements, lower specificity

Q3. Semantic HTML Tags with meaning (<header>, <nav>, <main>, <article>, <footer>). Improves
accessibility, SEO, and code readability.

Q4. Meta Tags Provide metadata: charset, viewport, description, keywords, author.

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Q5. Font Icons vs SVG

• Font Icons: Single file, easy to style with CSS, but blurry when scaled

• SVG: Vector, crisp at any size, multicolor, accessible, but more markup

Q6. alt Attribute in <img> Provides alternative text for screen readers, displays if image fails to load,
important for accessibility and SEO.

Q7. data-* Attributes Custom data attributes for storing extra info: <div data-user-id="123"> Access:
[Link]

Q8. ARIA Attributes Accessibility attributes for assistive technologies: role, aria-label, aria-hidden,
aria-expanded

Q9. <canvas> HTML element for drawing graphics via JavaScript (2D and WebGL contexts).

Q10. <picture> Element Responsive images with multiple sources based on media queries:

<picture>
<source srcset="[Link]" media="(min-width: 800px)">
<source srcset="[Link]" media="(min-width: 400px)">
<img src="[Link]" alt="Responsive image">
</picture>

Generated by [Link]
React Interview Questions

Q1. React Lifecycle

• Mounting: constructor → render → componentDidMount

• Updating: render → componentDidUpdate

• Unmounting: componentWillUnmount

• (Hooks: useEffect replaces lifecycle methods)

Q2. State vs Props

• State: Internal, mutable, managed by component, triggers re-render

• Props: External, immutable, passed from parent, read-only

Q3. Pure Components Components that only re-render when props/state change (shallow compari-
son). [Link] or [Link]().

Q4. Higher-Order Components (HOC) Function that takes a component and returns an enhanced
component. Pattern for reusing logic.

Q5. Context API & useReducer

• Context API: Share data without prop drilling (createContext, useContext)

• useReducer: State management for complex state logic (like Redux but built-in)

Q6. [Link]() Code-splitting for components. Loads component only when needed.

const LazyComponent = [Link](() => import('./Component'));

Q7. Error Boundaries Components that catch JavaScript errors in child components and display
fallback UI.
class ErrorBoundary extends [Link] {
componentDidCatch(error, info) {
[Link]({ hasError: true });
}
}

Practice Resources

Resource URL Purpose

[Link] [Link] Comprehensive JS tutorial


JavaScript Questions [Link]/ Interview prep
lydiahallie/
javascript-questions
JS Interview Questions [Link]/sudheerj/ More interview prep
javascript-interview-
questions
Atlassian Git Cheat Sheet Atlassian PDF Git commands reference

Generated by [Link]
NASA API [Link] Practice with real API

Project Ideas
1. Ping-Pong Game — Canvas-based game with keyboard controls
2. Movie App — Fetch from TMDB API, display movies with search/filter
3. Todo App with LocalStorage — CRUD operations, persistent storage
4. Weather Dashboard — Fetch from weather API, display forecasts
5. Chat Application — Real-time messaging with WebSockets

Extra Topics to Explore


• Generator Functions: function* with yield for iterators
• Symbols: Unique primitive values (Symbol("desc"))
• Debouncing & Throttling: Control function execution rate
• Iterables & Iterators: Objects usable in for...of
• Strict Mode: "use strict"; — catches common mistakes

JavaScript Study Material compiled for Web Development Course — 2026

Generated by [Link]

You might also like