JavaScript Study Material
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
JavaScript is a scripting language — interpreted by the browser’s engine (V8 in Chrome). Modern
JS uses Just-In-Time (JIT) compilation for performance.
Tab Purpose
Generated by [Link]
Table 2 – continued
Tab Purpose
Console shortcuts:
[Link]("Debug message");
[Link]([{name: "A", age: 20}, {name: "B", age: 25}]);
[Link]("Error!");
[Link]("Warning!");
[Link]([Link]); // Object tree view
// 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
Reference: [Link]/type-conversions
// 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";
Generated by [Link]
2.2 Data Types
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"
Generated by [Link]
// No parameter type checking
function add(a, b) {
return a + b; // Could be numbers, strings, anything
}
// 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
try {
let x = undefinedVariable; // ReferenceError
} catch (error) {
[Link]([Link]); // "ReferenceError"
[Link]([Link]); // "undefinedVariable is not defined"
} finally {
[Link]("Always runs");
}
Generated by [Link]
4. Arrays & Objects
4.1 Arrays in JavaScript
// 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]
Generated by [Link]
// for...of (ES6) - iterates values
for (const fruit of fruits) {
[Link](fruit);
}
forEach vs map:
// 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)
const original = { a: 1, b: { c: 2 } };
Generated by [Link]
// Deep clone (modern method)
const deepClone2 = structuredClone(original);
Generated by [Link]
4.7 Set and Map
// 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();
}
Generated by [Link]
}
// [Link](blockVar); // ReferenceError
// IIFE variations
(function() { /* code */ }());
(() => { /* code */ })();
(async function() { /* code */ })();
5.3 Closures
function makeCounter() {
let count = 0; // Enclosed variable
return function() {
return ++count; // Remembers count from outer scope
};
}
[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)
}
Closure preserves scope: Even after the outer function finishes executing, the inner function retains
access to the outer function’s variables.
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)
}
};
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];
};
speak() {
return [Link] + " makes a sound";
}
Generated by [Link]
[Link] = breed;
}
speak() {
return [Link]() + " and barks!"; // Call parent method
}
}
8. DOM Manipulation
8.1 Accessing DOM Elements
// By ID (fastest)
const header = [Link]("header");
Differences:
Generated by [Link]
• HTMLCollection has length and index access, NodeList has forEach()
// 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");
});
// 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;";
Generated by [Link]
[Link](div, sibling); // Insert before specific element
[Link](div); // Remove element
// 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"
});
// 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!");
}
});
Generated by [Link]
[Link]("keypress", e => {
[Link]([Link]); // Letters, numbers only
});
// Stop propagation
[Link]("click", (e) => {
[Link](); // Stop bubbling up
[Link]("button only");
});
Reference: [Link]/bubbling-and-capturing
JavaScript runs on a single thread with one call stack. Asynchronous operations are handled by the
browser/Node APIs and placed in queues.
// 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
function fetchData(callback) {
setTimeout(() => {
const data = { id: 1, name: "John" };
callback(data);
}, 1000);
}
fetchData((data) => {
[Link](data);
});
Generated by [Link]
└──────────────┘ └─────────────┘ └─────────────┘
↑ │
└────────────────────────────────────────┘
(Event Loop)
Execution Order:
4. Repeat
[Link]("1"); // Sync
[Link]("4"); // Sync
// Output: 1, 4, 3, 2
// (Sync first, then microtasks, then macrotasks)
HTTP is stateless — each request is independent, server doesn’t remember previous requests.
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));
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 };
Generated by [Link]
const parsed = [Link](jsonString);
// { name: "John", age: 30 }
// [Link] options
[Link](obj, null, 2); // Pretty print with 2-space indentation
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
Generated by [Link]
promise
.then(result => [Link](result)) // "Data loaded!"
.catch(error => [Link](error)) // If rejected
.finally(() => [Link]("Done")); // Always runs
// [Link] / [Link]
[Link](42); // Instantly resolved
[Link]("err"); // Instantly rejected
12.3 Async/Await
// Usage
Generated by [Link]
getUserData(1)
.then(data => [Link](data))
.catch(err => [Link](err));
// 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" } };
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
// 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() { ... } }
Generated by [Link]
const value = userCount ?? 0; // Only for null/undefined, not 0 or ""
// BigInt
const huge = 9007199254740993n;
const alsoHuge = BigInt(9007199254740993);
14.2 Cookies
// Set cookie
[Link] = "username=John; expires=Fri, 31 Dec 2026 23:59:59 GMT; path=/; Secure;
↪ SameSite=Strict";
# 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
typeof 1; // "number"
typeof "number"; // "string"
// Answer: "string"
Generated by [Link]
• slice(start, end): Non-mutating, extracts portion
Q5. What is the Window Object Model (WOM)? The global object in browsers. Contains
document, location, navigator, screen, history, setTimeout, etc.
JavaScript — Intermediate
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).
Q5. Callback Hell & Event Loop Callback hell = deeply nested callbacks. Solved with Promises/
async-await. Event loop handles async execution order.
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).
Generated by [Link]
• NaN: Not a Number (invalid math operation)
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.
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).
• content-box: Width/height applies to content only (padding and border add to total)
Q6. % vs vh/vw
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; }
}
• 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).
Q2. id vs class
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">
• 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
• Unmounting: componentWillUnmount
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.
• useReducer: State management for complex state logic (like Redux but built-in)
Q6. [Link]() Code-splitting for components. Loads component only when needed.
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
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
Generated by [Link]