How to use this
- Read Sections 1 to 3, then do MCQs 1 to 11 and Coding 1 to 8. Type the code yourself, do not paste.
- Sleep. Then read Sections 4 to 6 and finish the remaining MCQs and coding questions.
- Last pass: open Exam traps, cover the answers, and say each result out loud before checking.
W19 to W25 means the topic is in your worksheets. Syllabus only means it is on the syllabus but not in W19 to W25, so I taught it from the syllabus line. Sections 5 and 6 are entirely that, and so are a few array topics in Section 2 and the callbacks part of Section 3.
1. JavaScript basics
W19W21
Why JavaScript, and how it gets onto a page
HTML gives structure, CSS gives style and simple hover effects, and JavaScript gives behaviour: counting cart items, reacting to clicks, changing the page. Without it, clicking "Add to Cart" does nothing.
Two ways to add it. Both run automatically when the page loads, no console typing needed.
<!-- inline: code sits inside the tag -->
<script>console.log("Hello from the page!");</script>
<!-- external: same idea as href in CSS, but the attribute is src -->
<script src="script.js"></script>
Put the tag right before </body> so the HTML exists before your code runs. External files win as projects grow: one file, reusable, cached, easier to read.
The console evaluates what you type and shows the result: 5 + 3 shows 8. It resets on refresh, which is why real code lives in a file.
Variables: var, let, const
A variable stores a value under a name so you can reuse and change it. A bare price = 10; works in the console but is not the proper way. Use a keyword.
var | let | const | |
|---|---|---|---|
| Redeclare same name | Allowed, no error | SyntaxError | SyntaxError |
| Reassign value | Yes | Yes | No (TypeError) |
| Scope | Function scope (ignores { } blocks) | Block scope | Block scope |
| Use before its line | undefined (hoisted) | ReferenceError (TDZ) | ReferenceError (TDZ) |
if (true) {
var a = "I'm var";
let b = "I'm let";
}
console.log(a); // "I'm var" (leaks out of the block)
console.log(b); // ReferenceError: b is not defined
console.log(x); // undefined (var is hoisted, value not)
var x = 5;
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 5;
- Default to
const. Switch toletonly when the value must be reassigned. Seeinglettells a reader "this changes". - Avoid
var: silent redeclaration and block leaking cause bugs. - Names are camelCase and meaningful:
cartTotal,isLoggedIn. Notcart_total, notCartTotal, notx. - Semicolons: JavaScript often works without them, but use them. It removes a class of surprising bugs.
Maths and datatypes
10 + 3 // 13
10 - 3 // 7
10 * 3 // 30
10 / 3 // 3.3333333333333335 (no integer division, you get a decimal)
10 % 3 // 1 (modulo = remainder after dividing)
2 ** 3 // 8 (power)
JavaScript has 8 datatypes: 7 primitives (string, number, boolean, undefined, null, bigint, symbol) and 1 non-primitive (object). A primitive is a single plain value, not a collection. Arrays and functions are special objects.
typeof 'Alex' // "string"
typeof 21 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (old bug, famous exam trap)
typeof [1, 2] // "object" (arrays are objects)
typeof NaN // "number" (NaN is "not a number" but its type is number)
typeof function(){} // "function"
Strings: joining and template literals
+ on strings is concatenation. It glues exactly what you give it. No spaces added.
let firstName = 'Nikhil', lastName = 'Bhatt';
console.log(firstName + lastName); // NikhilBhatt
console.log(firstName + ' ' + lastName); // Nikhil Bhatt
console.log(firstName, lastName); // Nikhil Bhatt (console.log itself puts a space between arguments)
+ works left to right. Once a string is involved, the rest becomes text.
let price = 28;
console.log('Total: ' + price + 5); // "Total: 285" ('Total: 28' is text, then + 5 appends "5")
console.log(price + 5 + ' total'); // "33 total" (28 + 5 first, then join the text)
console.log(1 + 2 + '3' + 4); // "334"
Template literals use backticks and ${ }. Anything inside ${ } is evaluated and its value dropped into the text. They fix the problem above and read like a sentence.
console.log(`Total: ${price + 5}`); // Total: 33
console.log(`Hello ${name}, your ${item} is ready!`);
Comparing and deciding
5 === 5 // true
5 === '5' // false strict: value AND type must match
5 == '5' // true loose: converts types first
5 !== '5' // true
5 != '5' // false
Loose == quietly converts, which gives odd results: 0 == false is true, "" == 0 is true, null == undefined is true. Professional code uses === and !== by default because the result is predictable.
if (age >= 18) {
console.log("adult");
} else if (age >= 13) {
console.log("teen");
} else {
console.log("child");
}
// logical operators: && (and), || (or), ! (not)
Loops
// for: start; condition; update (use when you know how many times)
for (let i = 1; i <= 5; i++) { console.log(i); } // 1 2 3 4 5
// while: you manage the counter yourself
let n = 1;
while (n <= 5) { console.log(n); n++; } // forget n++ and it loops forever
// do-while: body runs first, condition is checked after, so it runs AT LEAST once
let k = 10;
do { console.log(k); k++; } while (k < 5); // prints 10 once
Pick for when the count is known, while when you loop until something happens, do-while when the body must run once before you can decide (asking the user for input, for example).
alert, prompt, console.log and converting input
console.log(x)prints to the console. With several arguments it separates them with spaces.alert(msg)shows a popup and returns nothing.prompt(msg)asks the user to type. It always returns a string, ornullif they press Cancel.
| Function | Behaviour | Examples |
|---|---|---|
parseInt(str) | Reads leading whole-number digits, stops at the first bad character, drops decimals | parseInt("42px") is 42, parseInt("3.9") is 3 |
parseFloat(str) | Same, but keeps the decimal part | parseFloat("3.14 kg") is 3.14 |
Number(str) | Converts the whole string, any bad character gives NaN | Number("42") is 42, Number("42px") is NaN |
"21" + 1 is "211", not 22. And parseInt(null) (Cancel pressed) is NaN.The expense calculator from W21 is the pattern to know cold:
let total = 0;
let amount;
do {
amount = prompt("Enter an expense (or type 'done' to finish):");
if (amount !== "done") {
total += parseFloat(amount);
}
} while (amount !== "done");
console.log(`Total expenses: ${total}`);
Where does total go? Outside the loop. If you declare it inside, it resets to 0 on every pass and (with let) also disappears after the loop ends.
2. Objects and arrays
W20W22 Syllabus only for spread, structuredClone and most array methods.
Objects
One variable per detail does not scale: 500 students means thousands of names, and nothing ties a student's values together. An object keeps related data as key-value pairs (properties) under one name. Values can be any type, including other objects.
const student = {
name: "Likhilesh",
city: "Delhi",
college: "KRMU",
rollNumber: "2616400901"
};
typeof student; // "object"
Compared with a Python dict: same curly braces and commas, but keys are usually written without quotes and named in camelCase. JavaScript turns every key into a string.
CRUD on objects
// Create: the object literal above, or add a new key
student.phone = "9999999999";
// Read
student.name; // dot notation
student["city"]; // bracket notation, key is a string (works with variables: student[key])
student.country; // undefined (missing key, NO error; Python would raise KeyError)
// Update: same syntax as adding. Key exists = replace, key missing = add.
student.city = "Mumbai";
// Delete
delete student.name;
delete student["city"];
const student = {...} only locks the name. You can add, change and delete properties freely. student = { name: "Someone Else" } throws TypeError: Assignment to constant variable.Copy by reference
const student2 = student; // NOT a copy: a second name for the same object
student2.city = "Jaipur";
console.log(student.city); // "Jaipur" (changed through either name)
Arrays behave the same way. Make a real copy with spread (shallow) or structuredClone (deep):
const copy1 = { ...student }; // shallow copy: new top-level object
const copy2 = [...fruits]; // shallow copy of an array
const deep = structuredClone(student); // deep copy: nested objects and arrays are copied too
const o = { title: "Web", topics: ["HTML"] };
const s = { ...o };
s.topics.push("CSS");
console.log(o.topics); // ["HTML", "CSS"] shallow copy still SHARES the nested array
const d = structuredClone(o);
d.topics.push("JS");
console.log(o.topics); // ["HTML", "CSS"] unchanged, deep copy is independent
Arrays
An ordered list in [ ]. It is a special object whose keys are indexes starting at 0, so typeof says "object". Check with Array.isArray(x).
const fruits = ["Mango", "Grapes"];
fruits[0]; // "Mango"
fruits.length; // 2
fruits[fruits.length - 1]; // "Grapes" (last item: Python's lst[-1])
fruits[-1]; // undefined (no negative indexes)
fruits[2] = "Apple"; // fine, next free index
fruits[20] = "Watermelon"; // creates HOLES: indexes 3 to 19 are empty, length becomes 21
Because indexing past the end creates holes and a wrong length, use methods:
| JavaScript | Python | Does |
|---|---|---|
arr.push(x) | append | Add to end |
arr.unshift(x) | insert(0, x) | Add to start |
arr.pop() | pop() | Remove last (returns it) |
arr.shift() | pop(0) | Remove first (returns it) |
arr.splice(i, 0, x) | insert(i, x) | Insert at index i |
arr.splice(i, 1) | del lst[i] | Remove the item at i |
arr.splice(i, 1, x) | lst[i] = x | Replace the item at i |
splice(start, deleteCount, ...itemsToInsert) goes to start, removes deleteCount items, then inserts what you listed. One method does Create, Update and Delete.
const f = ["a", "b", "c", "d"];
f.splice(1, 2, "x"); // remove "b","c" and insert "x"
console.log(f); // ["a", "x", "d"]
delete f[1]; // BAD: leaves an empty hole, length unchanged
fruits[1] = "Orange" is safe because index 1 already exists, so it replaces and creates no hole.
Built-in array methods
Syllabus only Learn these well: they are how real code loops over data.
const nums = [4, 19, 7, 12];
nums.forEach(n => console.log(n)); // runs a function per item, returns nothing
nums.map(n => n * 2); // [8, 38, 14, 24] new array, same length
nums.filter(n => n > 8); // [19, 12] keeps items where test is true
nums.find(n => n > 8); // 19 first match (or undefined)
nums.reduce((sum, n) => sum + n, 0); // 42 fold to one value; 0 is the start
nums.includes(7); // true
nums.indexOf(7); // 2 (-1 if absent)
nums.join("-"); // "4-19-7-12"
nums.slice(1, 3); // [19, 7] copy a part, original untouched
[10, 9, 1].sort(); // [1, 10, 9] default sort compares as TEXT!
[10, 9, 1].sort((a, b) => a - b); // [1, 9, 10] numeric sort
slice does not change the array. splice does. map and filter return new arrays and leave the original alone.Spread and destructuring
const a = [1, 2], b = [3];
[...a, ...b]; // [1, 2, 3]
{ ...{ x: 1, y: 2 }, y: 9 }; // { x: 1, y: 9 } later keys win
Math.max(...[3, 9, 2]); // 9 spread values into arguments
Destructuring unpacks into variables in one line.
const student = { name: "Ajay", age: 20, rollNumber: "2616400901" };
const { name, age } = student; // matches by KEY NAME
const { rollNumber, city } = student; // city is undefined (no such key, no error)
const { name: studentName } = student; // rename while unpacking
const { city: c = "Pune" } = student; // default when missing
const fruits = ["Apple", "Banana", "Mango"];
const [first, second] = fruits; // matches by POSITION, any names you like
const [x, , z] = fruits; // skip with an empty slot: x = Apple, z = Mango
Object destructuring matches by name, array destructuring by position. It is not a deep copy: primitives are copied, but if the value is an array or object, the new variable points at the same one.
const course = { title: "Web Dev", topics: ["HTML", "CSS"] };
let { title, topics } = course;
title = "Full Stack"; // course.title is still "Web Dev"
topics.push("JS"); // course.topics is now ["HTML","CSS","JS"] (same array)
Comparing objects and arrays
When both sides are objects (arrays included), == and === compare references, not contents. They are true only if both sides are the very same object in memory.
const s1 = { name: "Ajay" };
const s2 = { name: "Ajay" };
const s3 = s1;
s1 == s2; // false different objects, even though they look identical
s1 === s2; // false
s1 === s3; // true same object
[1, 2] === [1, 2]; // false
[5] == 5; // true loose == converts the array to the text "5", then to 5
[5] === 5; // false strict never converts, and the types differ
[1, 2] == "1,2"; // true array becomes the text "1,2"
Trust ===. To compare contents you compare property by property (or compare JSON.stringify of both).
Working with API data
Real data is an object holding an array of objects. From W22, the API answer looks like this:
const data = {
products: [
{ title: "Honey Jar", price: 6.99 },
{ title: "Ice Cream", price: 5.49 },
{ title: "Kiwi", price: 2.49 }
],
total: 100, skip: 25, limit: 3
};
// print each item in INR (1 USD = 100 INR, rounded)
for (let i = 0; i < data.products.length; i++) {
const p = data.products[i];
console.log(p.title + " : " + Math.round(p.price * 100)); // Honey Jar : 699
}
// total price
let total = 0;
for (let i = 0; i < data.products.length; i++) total += data.products[i].price;
// name of the priciest item
let best = data.products[0];
for (let i = 1; i < data.products.length; i++) {
if (data.products[i].price > best.price) best = data.products[i];
}
console.log(best.title);
3. Functions
W22W23W24 Syllabus only for callbacks and higher-order functions.
The core ideas
A function is a named block you write once and run whenever you need it. Defining only stores it. The code runs when you call it.
function greetStudent(name) { // name = PARAMETER (in the definition)
console.log(`Hello, ${name}!`);
}
greetStudent("Ajay"); // "Ajay" = ARGUMENT (the actual value passed in)
greetStudent("Ravi"); // name is "Ravi" during this call
- Parameter is the name in the definition. Argument is the value in the call.
return valuesends a value back to the caller and ends the function immediately. Code after it never runs.- No
returnmeans the call gives backundefined. Printing withconsole.loginside is not returning. - Too few arguments: the missing parameter is
undefined. Too many: extras are ignored, no error. - Default value
function welcome(name = "Guest")is used when the argument is missing orundefined. It is not used fornull.
function add(a, b) { console.log(a + b); }
let result = add(2, 3); // prints 5; result is undefined
add(10, 20) * 2; // prints 30; then undefined * 2 = NaN
function sum(a, b) { return a + b; }
sum(10, 20) * 2; // 60 works because a value came back
function check() { return "done"; console.log("never printed"); }
introduce("Ajay"); // second parameter city is undefined
welcome(); // "Welcome, Guest!"
welcome(undefined); // "Welcome, Guest!"
welcome(null); // "Welcome, null!"
Why functions at all? In the INR example, the line Math.round(price * 100) was repeated three times. If the rate changed to 90, you would edit it three places. Put it in toINR(usd) once, and edit one place.
function toINR(usd) { return Math.round(usd * 100); }
function printPrice(item, usd) { console.log(item + " : " + toINR(usd)); }
printPrice("Honey Jar", 6.99); // Honey Jar : 699
Local scope and functions calling functions
A let/const inside a function exists only while the function runs and is invisible outside. Code inside can see outer variables. Code outside cannot see inner ones. An inner variable with the same name as an outer one shadows it and leaves the outer one untouched.
function calculateBMI(weight, height) {
const bmi = weight / (height * height);
return bmi;
}
calculateBMI(70, 1.75); // 22.857142857142858
console.log(bmi); // ReferenceError: bmi is not defined (it was local)
let city = "Pune";
function showCity() { let city = "Delhi"; console.log(city); }
showCity(); // Delhi
console.log(city); // Pune
Functions can call other functions. Build small helpers and combine them:
function square(n) { return n * n; }
function cube(n) { return n * n * n; }
function sumOfSquareAndCube(n) { return square(n) + cube(n); }
sumOfSquareAndCube(3); // 9 + 27 = 36
function isPositive(n) { return n >= 0; } // already a boolean, no if needed
function absoluteValue(n) { return isPositive(n) ? n : -n; }
function safeSquareRoot(n) { return Math.sqrt(absoluteValue(n)); }
Execution context and the call stack
Before running, JavaScript builds an execution context in two phases:
- Memory phase: it scans the code and reserves space.
vargetsundefined,let/constare reserved but unusable (the temporal dead zone), and a function declaration gets the whole function. - Code phase: it runs line by line, filling in real values and calling functions.
Hoisting is the visible effect: declarations are known before any line runs. So a function declaration can be called before it is written, var reads as undefined, and let/const throw a ReferenceError.
sayHi(); // "Hi!" works: declaration is hoisted whole
function sayHi() { console.log("Hi!"); }
console.log(x); var x = 5; // undefined
console.log(y); let y = 10; // ReferenceError (TDZ)
The very first context is the Global Execution Context (GEC), at the bottom of the call stack. Every function call pushes a new context on top. A return pops it off and control goes back to the one below. Local variables die with their context.
Trace of sumOfSquareAndCube(3):
1. [GEC] script starts
2. [GEC, sumOfSquareAndCube] call pushed
3. [GEC, sumOfSquareAndCube, square] square(3) called
4. [GEC, sumOfSquareAndCube] square returns 9, popped
5. [GEC, sumOfSquareAndCube, cube] cube(3) called
6. [GEC, sumOfSquareAndCube] cube returns 27, popped <-- "after cube returns"
7. [GEC] sumOfSquareAndCube returns 9 + 27 = 36, popped
GEC stays until the whole script ends.
Variables from the W24 breakpoint demo: before line 1 runs, b (var) already exists as undefined and multiplyByTwo already holds the whole function. a (let) is listed under "Script" and is unusable until its line runs. The log after return never prints.
Function expressions, arrow functions, callbacks
Syllabus only Functions are values. You can store them in variables, pass them as arguments, and return them.
const double = function (n) { return n * 2; }; // function expression
const triple = (n) => n * 3; // arrow function, one expression returns itself
const add = (a, b) => { return a + b; }; // braces need an explicit return
A callback is a function you pass into another function so it can be called later. A function that takes or returns functions is a higher-order function. map, filter, forEach, reduce and setTimeout are all higher-order.
function applyToAll(arr, fn) { // fn is a callback
const out = [];
for (let i = 0; i < arr.length; i++) out.push(fn(arr[i]));
return out;
}
applyToAll([1, 2, 3], triple); // [3, 6, 9]
applyToAll([1, 2, 3], n => n + 100); // [101, 102, 103]
function makeMultiplier(m) { return n => n * m; } // returns a function
const timesFour = makeMultiplier(4);
timesFour(5); // 20
applyToAll(arr, triple) is right, applyToAll(arr, triple()) calls it immediately and passes NaN.4. The browser and the page
W24W25
The BOM: window
The browser gives JavaScript one global object, window. Everything the browser provides hangs off it: console, alert, prompt, location, document. Writing window. is optional, so window.alert("Hi") and alert("Hi") are the same.
let userName = prompt("Your name?"); // typed text as a string, or null if Cancel pressed
alert("Hello " + userName); // "Hello null" after Cancel
// page address: https://shop.com/products/list?id=5
location.href; // whole URL: "https://shop.com/products/list?id=5"
location.hostname; // "shop.com"
location.pathname; // "/products/list"
location.search; // "?id=5"
location.href = "https://zenithschool.ai"; // assigning navigates to that page
document.title; // the tab title
document.title = "My Page"; // changes the tab title
The DOM tree
The browser turns your HTML into a tree of nodes. document is the root. Every tag, and the text inside it, becomes a node. A node's children are the tags written directly inside it. The chain to an h4 inside the card of the W25 page is document > html > body > main#root > div.card > div.product-info > h4. The children of div.card are the img and the div.product-info.
document.body.children includes <script> elements because they sit inside <body> in your HTML.
Selecting elements
| Method | Returns | Note |
|---|---|---|
getElementById("title") | One element (or null) | No #: the name already says id |
getElementsByClassName("item") | Collection (HTMLCollection) | No .. No forEach on it |
querySelector(".item") | First match only (or null) | Needs CSS syntax: . for class, # for id |
querySelectorAll(".item") | All matches (NodeList) | Has .length and forEach |
document.querySelector("#list .special"); // CSS selector: .special inside #list
Changing the page
const title = document.getElementById("title");
title.style.color = "crimson";
title.style.backgroundColor = "lightyellow"; // camelCase, not background-color (a hyphen is minus in JS)
const note = document.querySelector(".note"); // <p class="note">Prices in <b>INR</b></p>
note.innerText; // "Prices in INR" just the visible text
note.innerHTML; // "Prices in <b>INR</b>" the markup inside
note.innerText = "Prices in <i>USD</i>"; // shows the tags literally as text
note.innerHTML = "Prices in <i>USD</i>"; // renders USD in italics
innerText treats what you give it as plain text. innerHTML treats it as HTML. Use innerHTML when you want tags to take effect.
// W24 Q17: every .item blue, heading shows the count
const items = document.querySelectorAll(".item");
for (let i = 0; i < items.length; i++) {
items[i].style.color = "blue";
}
document.getElementById("title").innerText = `My Shop (${items.length} items)`;
Creating elements and rendering from data
document.createElement("tag") builds an element in memory only. It is invisible until you attach it with parent.appendChild(el), which adds it as the last child.
const newItem = document.createElement("li");
newItem.innerText = "Eraser"; // still not on the page
document.getElementById("list").appendChild(newItem); // NOW it appears
Dynamic rendering means building the page from data instead of typing the HTML. The recipe: data in an object, one card built from it, many cards built in a loop, all wrapped in a function.
const products = [
{ title: "Bag", price: "$200", rating: 4.2, thumbnail: "bag.jpg" },
{ title: "Mat", price: "$100", rating: 3.9, thumbnail: "mat.jpg" }
];
function main(arr) {
const root = document.getElementById("root");
for (let i = 0; i < arr.length; i++) {
const newCard = document.createElement("div"); // fresh element every iteration
newCard.className = "card"; // same as class="card" in HTML
newCard.innerHTML = `
<img src="${arr[i].thumbnail}" />
<div class="product-info">
<h4>${arr[i].title}</h4>
<p>Price: ${arr[i].price}</p>
<p>Rating: ${arr[i].rating}</p>
</div>`;
root.appendChild(newCard);
}
}
main(products);
- The second card does not replace the first because each iteration creates a new element and
appendChildadds it after the existing ones. - To show a third product you change zero lines in
main. You only add one object to the array. That is the whole point of data-driven rendering. - Changing a price means editing the object, not the HTML.
5. Events and forms
Syllabus only No worksheet from W19 to W25 covers this. It is taught here from the syllabus lines "responding to user actions through events triggered from HTML" and "handling forms, showing the details as a card".
Events from HTML
An event is something the user does: click, type, submit, hover. You attach a function to run when it happens. The simplest way is an HTML attribute that names your function. The function must be defined in your JavaScript file at top level.
<button onclick="addToCart()">Add to Cart</button>
<p>Items in cart: <span id="count">0</span></p>
let cartCount = 0;
function addToCart() {
cartCount++;
document.getElementById("count").innerText = cartCount;
}
- Attribute names:
onclick,onchange,oninput,onsubmit,onkeyup,onmouseover. onclick="addToCart()"needs the parentheses. They are the call. Writingonclick="addToCart"does nothing.- Pass data to the handler:
onclick="addToCart(3)"oronclick="show(event)"to receive the event object. - Same thing in JavaScript:
button.addEventListener("click", addToCart). Here you pass the function without parentheses, because you want to hand it over, not call it now.
Forms
Submitting a form makes the browser reload the page by default, wiping everything JavaScript built. Call event.preventDefault() first thing to stop that. Read what the user typed from each input's .value. It is always a string.
<form onsubmit="handleSubmit(event)">
<input id="titleInput" placeholder="Title">
<input id="priceInput" placeholder="Price">
<button type="submit">Add</button>
</form>
<div id="list"></div>
function handleSubmit(event) {
event.preventDefault(); // stop the page reload
const title = document.getElementById("titleInput").value;
const price = parseFloat(document.getElementById("priceInput").value); // string to number
const card = document.createElement("div");
card.className = "card";
card.innerHTML = `<h4>${title}</h4><p>Price: $${price}</p>`;
document.getElementById("list").appendChild(card);
event.target.reset(); // clear the form (event.target is the form)
}
"$${price}" prints a literal dollar sign followed by the value. .value of a number input is still text: "5" + "5" is "55".6. Asynchronous JavaScript
Syllabus only No worksheet from W19 to W25 covers this. Taught from the syllabus lines on delays, the event loop, success and failure paths, API calls and rendering a products page.
Running code after a delay, and the event loop
JavaScript does one thing at a time (single thread). Slow things like timers and network calls are handed to the browser, and their callbacks are run later, once the stack is empty.
console.log("A");
setTimeout(() => console.log("B"), 0); // timer callback goes to the task queue
Promise.resolve().then(() => console.log("C")); // promise callback goes to the microtask queue
console.log("D");
// A D C B
The event loop order: 1) run all synchronous code on the call stack, 2) run all queued microtasks (promise callbacks), 3) run one task (a timer callback), then repeat. That is why even setTimeout(fn, 0) waits until all normal code has finished.
setTimeout(sayHi, 2000); // runs sayHi once after 2000 ms. Pass sayHi, NOT sayHi()
const id = setInterval(tick, 1000); // runs tick every 1000 ms until stopped
clearInterval(id);
Promises: separate paths for success and failure
A promise stands for a result that is not ready yet. It is pending, then either fulfilled (success, with a value) or rejected (failure, with a reason).
const p = new Promise((resolve, reject) => {
setTimeout(() => {
const ok = true;
if (ok) resolve("data ready"); // success path
else reject("something broke"); // failure path
}, 1000);
});
p.then(value => console.log(value)) // runs on success
.catch(error => console.log(error)) // runs on failure
.finally(() => console.log("done")); // runs either way
Calling an API: fetch, then async/await
fetch(url) returns a promise for the response. response.json() is also a promise. Chained version:
fetch("https://dummyjson.com/products?limit=10")
.then(res => res.json())
.then(data => console.log(data.products))
.catch(err => console.log("Failed:", err));
async/await is the same thing in a clean, top-to-bottom style. await pauses that function until the promise settles and gives you the value. It only works inside an async function. Use try/catch for the failure path. An async function always returns a promise.
async function loadProducts() {
try {
const res = await fetch("https://dummyjson.com/products?limit=10");
if (!res.ok) throw new Error("HTTP " + res.status); // fetch does NOT reject on 404/500
const data = await res.json();
return data.products;
} catch (err) {
console.log("Failed:", err.message);
return [];
}
}
console.log(loadProducts()) prints a Promise, not the array. You need await (or .then) to get the value.Putting it together: a products page with Add to Cart
<main id="root"></main>
<p>Cart: <span id="cartCount">0</span></p>
const cart = [];
let allProducts = [];
function addToCart(id) {
const product = allProducts.find(p => p.id === id);
cart.push(product);
document.getElementById("cartCount").innerText = cart.length;
}
function render(arr) {
const root = document.getElementById("root");
root.innerHTML = ""; // clear old cards before drawing
for (let i = 0; i < arr.length; i++) {
const card = document.createElement("div");
card.className = "card";
card.innerHTML = `
<img src="${arr[i].thumbnail}" />
<h4>${arr[i].title}</h4>
<p>Price: $${arr[i].price}</p>
<button onclick="addToCart(${arr[i].id})">Add to Cart</button>`;
root.appendChild(card);
}
}
async function main() {
try {
const res = await fetch("https://dummyjson.com/products?limit=10");
const data = await res.json();
allProducts = data.products;
render(allProducts);
} catch (err) {
document.getElementById("root").innerText = "Could not load products.";
}
}
main();
Order of events: the page loads, main() starts, await fetch hands the request to the browser and the rest of the page keeps going. When the response arrives, the function resumes, stores the data and renders cards. Each button's onclick has the product id baked in, so the click handler knows which product to add.
MCQ practice
Seventeen predict-the-output and concept questions, same style as the midsem. Answer first, then read the reason. Wrong answers are the most useful ones to reread.
Coding practice
Thirteen questions, easy to hard. Write the code in the box and press Run tests. Tests call your function with several inputs, including edge cases. Try for at least ten minutes before opening the hint, and the solution last. Press Tab inside the box to indent.
If you accidentally write a loop that never ends, the tab will freeze. Reload the page to recover. Questions 11 and 12 run against a scratch copy of the page, so your DOM code never touches this page.
Exam traps
Cover the right-hand column, say the answer, then check. Every line is something a question can be built on.
| Expression or situation | Result and reason |
|---|---|
'Total: ' + 28 + 5 | "Total: 285". Left to right, string first. |
28 + 5 + ' total' | "33 total". Numbers added before the string appears. |
10 / 3 and 10 % 3 | 3.3333333333333335 and 1. |
typeof null, typeof [], typeof NaN | "object", "object", "number". |
5 == '5' vs 5 === '5' | true vs false. Loose converts, strict checks type too. |
var read before its line | undefined. Hoisted, value not yet assigned. |
let/const read before its line | ReferenceError. Temporal dead zone. |
Redeclare with var / let | Fine / SyntaxError. |
var inside if { }, read outside | Works. var ignores blocks. let would be a ReferenceError. |
| Function declaration called before it is written | Works. Whole function is hoisted. |
Change a property of a const object | Allowed. Only reassigning the name throws. |
const b = a where a is an object or array | Same object, two names. Change through one, see it in both. |
Missing key: obj.phone | undefined, no error. |
arr[-1] | undefined. Last item is arr[arr.length - 1]. |
a = [1,2,3]; a[5] = 6; a.length | 6, with two empty holes. |
delete arr[1] | Leaves a hole, length unchanged. Use splice. |
["a","b","c","d"].splice(1, 2, "x") | Array becomes ["a","x","d"]. |
[1,2] === [1,2] | false. Different objects. References are compared. |
[5] == 5, [5] === 5 | true, false. |
const { city } = { name: "A" } | city is undefined. Object destructuring matches by key name. |
Destructure an array out of an object, then push | Original changes too. Destructuring is not a deep copy. |
Spread { ...o } with a nested array inside | Nested array still shared. Use structuredClone for a deep copy. |
Function with no return | Gives undefined. add(2,3) * 2 is NaN. |
Code after return | Never runs. |
welcome(undefined) vs welcome(null) with name = "Guest" | Uses "Guest" vs uses null. |
| Call with fewer / more arguments than parameters | Missing is undefined / extras ignored, no error. |
| Same variable name inside and outside a function | Inner one shadows. Outer one unchanged. |
prompt() returns | A string, or null on Cancel. |
parseInt("42px"), Number("42px"), parseInt("3.9") | 42, NaN, 3. |
do { } while (false) | Body still runs once. |
[10, 9, 1].sort() | [1, 10, 9]. Text order. Use (a, b) => a - b. |
getElementById vs querySelector | No # needed vs CSS selector needed. |
getElementsByClassName / querySelectorAll | Collection / NodeList. Both have .length. forEach only on NodeList. |
el.style.background-color | Wrong. Write el.style.backgroundColor. |
innerText = "<i>Hi</i>" | Shows the tags as text. innerHTML would italicise. |
createElement without appendChild | Nothing on the page. |
| Loop that appends a new card each pass | Cards add up, none replaced. A third product needs zero changes inside the function. |
onclick="fn()" vs onclick="fn" | Calls on click vs does nothing. |
| Form submit handler | Start with event.preventDefault(). .value is always a string. |
A, setTimeout B (0 ms), promise C, D | Prints A D C B. Sync, then microtasks, then timers. |
async function result without await | A Promise, not the value. |
fetch on a 404 | Does not reject. Check res.ok. |