Loops repeat code: check every row in a table, retry a request until it succeeds, run the same test with ten sets of data. JavaScript has several loop types, and choosing the right one makes code shorter and avoids bugs such as skipping the last item or looping forever. In this lesson you will learn every loop, the difference between for...of and for...in, nested loops, and the important rule for using await inside loops.
📖 What You’ll Learn: the for loop and its three parts, while and do…while, for…of for arrays, strings and Maps, for…in for object keys, Array.forEach, Object.entries, nested loops, infinite loops and how to avoid them, off-by-one errors, choosing the right loop, and await inside loops.
🔁 What Is a Loop?
Definition: a loop runs a block of code repeatedly, either a fixed number of times or while a condition stays true. Each run of the block is called an iteration.
Loop
Best for
for
Counting: a known number of iterations, or when you need the index
while
Repeating until a condition changes (unknown number of iterations)
do...while
Like while, but the body must run at least once
for...of
Values of arrays, strings, Maps, Sets
for...in
Keys (property names) of an object
array.forEach()
Calling a function for each array item
🔢 The for Loop
A for loop has three parts in its parentheses, separated by semicolons:
📄 Syntax
for (initialisation; condition; update) {
// body
}
Initialisation runs once before the loop, usually let i = 0.
Condition is checked before every iteration; the loop stops when it is falsy.
Update runs after every iteration, usually i++.
📄 for.js
for (let i = 1; i <= 5; i++) {
console.log(`Run ${i} of 5`);
}
const browsers = ["chromium", "firefox", "webkit"];
for (let i = 0; i < browsers.length; i++) {
console.log(i, browsers[i]);
}
for (let i = 10; i > 0; i -= 3) { // counting down in steps of 3
console.log("countdown", i);
}
⌨️ Terminal
node for.js
🖥️ Output
Run 1 of 5
Run 2 of 5
Run 3 of 5
Run 4 of 5
Run 5 of 5
0 chromium
1 firefox
2 webkit
countdown 10
countdown 7
countdown 4
countdown 1
⚠️ Watch out:Off-by-one errors are the most common loop bug. Array indexes go from 0 to length - 1, so the condition is i < arr.length, not i <= arr.length. Using <= reads one item past the end, which is undefined.
📄 off-by-one.js
const items = ["pen", "book"];
for (let i = 0; i <= items.length; i++) { // bug: <= instead of <
console.log(i, items[i]);
}
⌨️ Terminal
node off-by-one.js
🖥️ Output
0 pen
1 book
2 undefined
⏳ The while Loop
A while loop checks its condition before each iteration and runs as long as it is truthy. Use it when you do not know in advance how many iterations you need.
📄 while.js
let attempt = 0;
let connected = false;
while (!connected && attempt < 5) {
attempt++;
connected = attempt === 3; // pretend the 3rd attempt works
console.log(`Attempt ${attempt}: ${connected ? "connected" : "failed"}`);
}
console.log(connected ? "Ready" : "Gave up after 5 attempts");
⚠️ Watch out: If nothing inside the loop ever makes the condition false, you get an infinite loop and the program hangs. Always change something the condition depends on, and add a safety limit such as attempt < 5. Stop a hanging Node.js script with Ctrl+C.
🔂 The do…while Loop
do...while runs the body first and checks the condition afterwards, so the body always runs at least once.
📄 do-while.js
let page = 1;
const totalPages = 1; // the API reports only one page
do {
console.log(`Fetching page ${page}`);
page++;
} while (page <= totalPages);
let count = 10;
while (count < 5) {
console.log("while: never printed");
}
do {
console.log("do...while: printed once even though 10 < 5 is false");
} while (count < 5);
⌨️ Terminal
node do-while.js
🖥️ Output
Fetching page 1
do...while: printed once even though 10 < 5 is false
📋 for…of: Loop Over Values
for...of loops over the values of an iterable: arrays, strings, Maps, Sets and more. It is the cleanest loop for arrays when you do not need the index.
📄 for-of.js
const tests = ["login", "search", "checkout"];
for (const test of tests) {
console.log("running", test);
}
for (const ch of "QA!") {
console.log(ch);
}
const scores = new Map([["asha", 91], ["ravi", 78]]);
for (const [name, score] of scores) {
console.log(name, score);
}
for (const [index, test] of tests.entries()) { // value and index
console.log(index + 1, test);
}
⌨️ Terminal
node for-of.js
🖥️ Output
running login
running search
running checkout
Q
A
!
asha 91
ravi 78
1 login
2 search
3 checkout
💡 Tip: Use const in for...of when you do not reassign the loop variable. Each iteration gets a fresh binding, so const is allowed.
🗝️ for…in: Loop Over Object Keys
for...in loops over the keys (property names) of an object. Read the value with bracket notation obj[key].
📄 for-in.js
const config = { browser: "chromium", headless: true, retries: 2 };
for (const key in config) {
console.log(`${key} = ${config[key]}`);
}
// Object.entries gives key and value together, and works with for...of
for (const [key, value] of Object.entries(config)) {
console.log(key.padEnd(9), "->", value);
}
⚠️ Watch out: Do not use for...in on arrays. It gives you the indexes as strings and also includes any extra properties added to the array. Use for...of, a classic for or forEach for arrays.
📄 for-in-array.js
const list = ["a", "b"];
list.note = "extra property";
for (const i in list) {
console.log(i, typeof i);
}
for (const value of list) {
console.log(value);
}
⌨️ Terminal
node for-in-array.js
🖥️ Output
0 string
1 string
note string
a
b
for...of
for...in
Gives you
Values
Keys (as strings)
Works on
Iterables: arrays, strings, Map, Set
Objects (any object)
Use for arrays?
Yes
No
Plain objects
No (TypeError: not iterable) — use Object.entries()
Yes
🧾 Array.forEach
array.forEach(callback) calls a function once for every item, passing the item, its index and the array. It is common in existing code.
📄 foreach.js
const prices = [120, 80, 45];
let total = 0;
prices.forEach((price, index) => {
console.log(`item ${index + 1}: ${price}`);
total += price;
});
console.log("total", total);
⌨️ Terminal
node foreach.js
🖥️ Output
item 1: 120
item 2: 80
item 3: 45
total 245
You cannot stop forEach early with break; use for...of or some()/find() when you need to stop.
forEach does not wait for async callbacks (see the last section).
To build a new array from an existing one, map() and filter() are better choices (Module 6).
🪆 Nested Loops
A loop inside another loop runs the inner loop completely for every iteration of the outer loop. A common use is combining two lists, for example every browser with every viewport:
📄 nested.js
const browsers = ["chromium", "firefox"];
const viewports = ["mobile", "desktop"];
for (const browser of browsers) {
for (const viewport of viewports) {
console.log(`test on ${browser} / ${viewport}`);
}
}
// A multiplication table: rows x columns
for (let r = 1; r <= 3; r++) {
let row = "";
for (let c = 1; c <= 4; c++) {
row += String(r * c).padStart(4);
}
console.log(row);
}
⌨️ Terminal
node nested.js
🖥️ Output
test on chromium / mobile
test on chromium / desktop
test on firefox / mobile
test on firefox / desktop
1 2 3 4
2 4 6 8
3 6 9 12
The total work is outer × inner iterations. Two lists of 1,000 items already means 1,000,000 iterations, so watch nested loops on large data.
⏱️ Loops and await (Important for Playwright)
Test code is full of await (you will learn promises and async/await in Module 10). The rule to remember now: await works inside for, for...of and while, but forEach does not wait.
📄 await-loop.js
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function main() {
console.log("--- for...of waits for each step ---");
for (const step of ["open", "login", "verify"]) {
await sleep(10);
console.log("done:", step);
}
console.log("all steps finished");
console.log("--- forEach does NOT wait ---");
["open", "login", "verify"].forEach(async (step) => {
await sleep(10);
console.log("done:", step);
});
console.log("forEach returned (steps still running!)");
}
main();
⌨️ Terminal
node await-loop.js
🖥️ Output
--- for...of waits for each step ---
done: open
done: login
done: verify
all steps finished
--- forEach does NOT wait ---
forEach returned (steps still running!)
done: open
done: login
done: verify
⚠️ Watch out: In a Playwright test, items.forEach(async (item) => { await page.click(...) }) lets the test finish before the clicks happen, causing random failures. Use for (const item of items) { await ... } instead.
🧪 Tester Scenario: Data-Driven Checks
Running the same check with many inputs is called data-driven testing. A loop over a table of cases keeps it short:
Playwright supports the same idea directly: put a test() call inside a for...of loop over your cases, and each case appears as its own test in the report.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Print the even numbers from 2 to 20 with a for loop, all on one line.
Show answer
📄 practice1.js
let line = "";
for (let n = 2; n <= 20; n += 2) {
line += n + " ";
}
console.log(line.trim());
🖥️ Output
2 4 6 8 10 12 14 16 18 20
Q2. Calculate the sum and the average of [12, 7, 30, 5, 16] with a for...of loop.
Show answer
📄 practice2.js
const values = [12, 7, 30, 5, 16];
let sum = 0;
for (const v of values) {
sum += v;
}
console.log("sum", sum, "average", sum / values.length);
🖥️ Output
sum 70 average 14
Q3. Reverse the string "playwright" with a loop (without reverse()).
Show answer
📄 practice3.js
const word = "playwright";
let reversed = "";
for (let i = word.length - 1; i >= 0; i--) {
reversed += word[i];
}
console.log(reversed);
🖥️ Output
thgirwyalp
Q4. Count how many times each status appears in ["pass", "fail", "pass", "skip", "pass"], storing the counts in an object.
Show answer
📄 practice4.js
const statuses = ["pass", "fail", "pass", "skip", "pass"];
const counts = {};
for (const s of statuses) {
counts[s] = (counts[s] ?? 0) + 1;
}
console.log(counts);
for (const key in counts) {
console.log(`${key}: ${counts[key]}`);
}
Q5. Use a while loop to find the first power of 2 that is greater than 1000.
Show answer
📄 practice5.js
let power = 1;
let exponent = 0;
while (power <= 1000) {
power *= 2;
exponent++;
}
console.log(`2^${exponent} = ${power}`);
🖥️ Output
2^10 = 1024
Q6. Print a right-angled triangle of * with 5 rows using nested loops.
Show answer
📄 practice6.js
for (let row = 1; row <= 5; row++) {
let line = "";
for (let col = 1; col <= row; col++) {
line += "*";
}
console.log(line);
}
🖥️ Output
*
**
***
****
*****
A shorter alternative for each line is "*".repeat(row).
🧠 MCQ Quiz: Loops
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
How many times does for (let i = 0; i < 5; i++) run its body?
Answer: 5. i takes the values 0, 1, 2, 3 and 4.
Which loop always runs its body at least once?
Answer: do…while. The condition is checked after the body.
What does for (const x of ["a", "b"]) give you in x?
Answer: The values “a” and “b”. for…of iterates values.
What does for (const k in { a: 1, b: 2 }) give you in k?
Answer: The keys “a” and “b”. for…in iterates property names.
Why should you avoid for…in on arrays?
Answer: It gives string indexes and also extra properties. Use for…of or a classic for loop for arrays.
What happens with for (const x of { a: 1 })?
Answer: TypeError: object is not iterable. Plain objects are not iterable; use Object.entries(obj).
With arr = ["x", "y"], what is printed last by for (let i = 0; i <= arr.length; i++) console.log(arr[i])?
Answer: undefined. <= reads index 2, which does not exist: an off-by-one bug.
Which loop does not wait for await inside its callback?
Answer: array.forEach. forEach ignores the promises its async callback returns.
How many times does the inner body run?
for (let i = 0; i < 3; i++)
for (let j = 0; j < 4; j++)
count++;
Answer: 12. Outer × inner: 3 × 4.
How do you get both key and value when looping over an object with for…of?
Answer:for (const [k, v] of Object.entries(obj)). Object.entries returns an array of [key, value] pairs.
💼 Interview Questions and Answers
Q1. What is the difference between for…of and for…in?
for...of iterates the values of iterables (arrays, strings, Maps, Sets, generators) using the iterator protocol. for...in iterates the enumerable keys of any object, including inherited ones, as strings. Use for...of for arrays and for...in (or better Object.keys/Object.entries) for plain objects.
Q2. What is the difference between forEach and for…of?
forEach is an array method that calls a callback for each item; you cannot break out of it, return only ends the current callback, and it does not await async callbacks. for...of is a language loop: it supports break, continue and await, and works on any iterable, not only arrays. In async test code, prefer for...of.
Q3. A Playwright test loops over menu links with forEach and clicks each one, but it passes even when links are broken. Why?
The callback is async, and forEach ignores the promises it returns. The test function reaches its end, so the test is reported as passed, while the clicks and assertions run (and may fail) afterwards or are cancelled when the page closes. Fix: for (const link of links) { await link.click(); await expect(...)... }. Use Promise.all only when the steps can safely run in parallel.
Q4. How do you avoid infinite loops in retry logic?
Always bound the loop: a maximum attempt count or a deadline (Date.now() < start + timeout), update the variables the condition depends on inside the loop, and add a delay between attempts. After the loop, fail with a clear error that includes the last result. Built-in waiting tools (Playwright’s auto-waiting, expect.poll, toPass) handle this for you and are preferred in tests.
📄 bounded-retry.js
function retry(action, maxAttempts = 3) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const ok = action(attempt);
console.log(`attempt ${attempt}: ${ok ? "ok" : "failed"}`);
if (ok) return attempt;
}
throw new Error(`Failed after ${maxAttempts} attempts`);
}
retry((n) => n === 2);
try {
retry(() => false);
} catch (e) {
console.log(e.message);
}
⌨️ Terminal
node bounded-retry.js
🖥️ Output
attempt 1: failed
attempt 2: ok
attempt 1: failed
attempt 2: failed
attempt 3: failed
Failed after 3 attempts
Q5. What is an off-by-one error? Give an example.
A loop that runs one time too many or too few, usually because of <= versus < or starting at 1 instead of 0. Example: for (let i = 0; i <= arr.length; i++) reads arr[arr.length], which is undefined. Iterating values with for...of avoids index arithmetic entirely, and boundary tests (empty array, one item, last item) catch these bugs.
❓ Frequently Asked Questions
🤔 Which loop is fastest in JavaScript?
For normal data sizes the differences are tiny. Choose for readability: for...of for arrays, for when you need the index or a custom step, while for unknown iteration counts.
🤔 How do I loop through an object in JavaScript?
Use for (const [key, value] of Object.entries(obj)), or for...in for the keys. Object.keys() and Object.values() give arrays of keys or values.
🤔 How do I stop a loop early?
Use break to leave the loop or continue to skip to the next iteration. These are covered in the next lesson. They do not work in forEach.
🤔 Can I use await inside a for loop?
Yes, in an async function, await works in for, for...of, while and do...while, and each iteration waits. It does not work as expected inside forEach.
🏁 Summary
for counts with initialisation, condition and update; use i < arr.length to avoid off-by-one errors.
while repeats while a condition is true; do...while always runs at least once; always make sure the loop can end.
for...of gives values of arrays, strings, Maps and Sets; for...in gives object keys and should not be used on arrays.
forEach cannot break and does not wait for await; use for...of in async test code.
Loops over tables of inputs and expected results are the basis of data-driven testing.
Here are 20 JavaScript programs with solutions covering: ✔ if ✔ if-else ✔ if-else if ✔ nested if ✔ one-line (ternary) conditions
🔹 1. Positive number (if)
let num = 5;if (num > 0) { console.log("Positive"); }
🔹 2. Even or odd (if-else)
let num = 4;if (num % 2 === 0) { console.log("Even"); } else { console.log("Odd"); }
🔹 3. Voting eligibility (if-else)
let age = 16;if (age >= 18) { console.log("Eligible"); } else { console.log("Not eligible"); }
🔹 4. Largest of two numbers (if-else)
let a = 10, b = 20;if (a > b) { console.log("a is greater"); } else { console.log("b is greater"); }
🔹 5. Divisible by 3 (if)
let num = 9;if (num % 3 === 0) { console.log("Divisible by 3"); }
🔹 6. Grade system (if-else if)
let marks = 85;if (marks >= 90) { console.log("A"); } else if (marks >= 70) { console.log("B"); } else if (marks >= 50) { console.log("C"); } else { console.log("Fail"); }
🔹 7. Largest of three numbers (if-else if)
let a = 5, b = 8, c = 3;if (a > b && a > c) { console.log("a is largest"); } else if (b > c) { console.log("b is largest"); } else { console.log("c is largest"); }
🔹 8. Leap year (if-else)
let year = 2024;if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) { console.log("Leap year"); } else { console.log("Not leap year"); }
🔹 9. Check number range (if)
let num = 25;if (num >= 10 && num <= 50) { console.log("Within range"); }
Programs need to make decisions: retry when a request fails, show an error when a field is empty, mark a test as passed or failed. The if statement is how JavaScript decides which code to run. In this lesson you will learn if, else and else if, combine conditions safely, avoid deep nesting with guard clauses, and replace long if chains with lookup objects.
📖 What You’ll Learn: the if statement, if…else, else if chains and their order, conditions with comparison and logical operators, truthy checks, nested if statements, guard clauses and early returns, the ternary alternative, lookup objects, and common mistakes such as = instead of ===.
🚦 The if Statement
Definition: an if statement runs a block of code only when its condition is truthy. The condition goes in parentheses and the code in curly braces.
📄 Syntax
if (condition) {
// runs only when condition is truthy
}
📄 if.js
const statusCode = 500;
if (statusCode >= 500) {
console.log("Server error: retry the request");
}
console.log("Check finished"); // always runs
⌨️ Terminal
node if.js
🖥️ Output
Server error: retry the request
Check finished
The condition can be any expression. It is converted to a boolean using the truthy/falsy rules from the Truthy, Falsy and Equality lesson.
💡 Tip: JavaScript allows if (x) doSomething(); without braces for a single statement. Always use braces anyway: adding a second line later without braces is a classic bug, because only the first line belongs to the if.
↔️ if…else
else adds a block that runs when the condition is falsy. Exactly one of the two blocks runs.
📄 if-else.js
function checkLogin(password) {
if (password.length >= 8) {
console.log("Password accepted");
} else {
console.log(`Password too short: ${password.length} characters`);
}
}
checkLogin("secret123");
checkLogin("abc");
⌨️ Terminal
node if-else.js
🖥️ Output
Password accepted
Password too short: 3 characters
🪜 else if Chains
Use else if to test several conditions in order. JavaScript runs the first block whose condition is truthy and skips all the others.
📄 else-if.js
function grade(score) {
if (score >= 90) {
return "A";
} else if (score >= 75) {
return "B";
} else if (score >= 60) {
return "C";
} else {
return "F";
}
}
for (const s of [95, 82, 60, 41]) {
console.log(s, "->", grade(s));
}
⌨️ Terminal
node else-if.js
🖥️ Output
95 -> A
82 -> B
60 -> C
41 -> F
⚠️ Watch out: Order matters. If the first condition were score >= 60, a score of 95 would match it first and get a C. Put the most specific (or highest) conditions first.
📄 wrong-order.js
function gradeWrongOrder(score) {
if (score >= 60) return "C"; // matches 95 before the A check
else if (score >= 90) return "A";
return "F";
}
console.log(gradeWrongOrder(95));
Checkout allowed
Please log in
Cart is empty
Fix cart errors first
&&: all parts must be truthy.
||: at least one part must be truthy, for example if (role === "admin" || role === "owner").
!: negates a condition. Prefer positive names (isValid) so you rarely need double negatives.
When you compare one value with many options, includes is shorter than a long || chain:
📄 includes.js
const role = "editor";
if (role === "admin" || role === "owner" || role === "editor") {
console.log("can edit (|| chain)");
}
if (["admin", "owner", "editor"].includes(role)) {
console.log("can edit (includes)");
}
⌨️ Terminal
node includes.js
🖥️ Output
can edit (|| chain)
can edit (includes)
🪆 Nested if and Guard Clauses
An if can contain another if. A little nesting is fine, but deep nesting is hard to read:
📄 nested.js
function processOrder(order) {
if (order) {
if (order.items.length > 0) {
if (order.paid) {
return `Shipping order ${order.id}`;
} else {
return "Waiting for payment";
}
} else {
return "Order has no items";
}
} else {
return "No order";
}
}
console.log(processOrder({ id: 7, items: ["pen"], paid: true }));
⌨️ Terminal
node nested.js
🖥️ Output
Shipping order 7
Definition: a guard clause checks for an invalid case at the start of a function and returns early. The remaining code then handles only the normal case, with no nesting:
📄 guard.js
function processOrder(order) {
if (!order) return "No order";
if (order.items.length === 0) return "Order has no items";
if (!order.paid) return "Waiting for payment";
return `Shipping order ${order.id}`;
}
console.log(processOrder(null));
console.log(processOrder({ id: 8, items: [], paid: true }));
console.log(processOrder({ id: 9, items: ["lamp"], paid: false }));
console.log(processOrder({ id: 10, items: ["lamp"], paid: true }));
⌨️ Terminal
node guard.js
🖥️ Output
No order
Order has no items
Waiting for payment
Shipping order 10
💡 Tip: Guard clauses are the most useful refactoring for beginners. Test helpers, page objects and API clients written this way are much easier to read in a code review.
⚡ Shorter Alternatives: Ternary and Lookup Objects
When an if...else only chooses between two values, the ternary operator is shorter:
📄 ternary.js
const passed = 18, total = 20;
let verdict;
if (passed === total) {
verdict = "PASS";
} else {
verdict = "FAIL";
}
console.log(verdict);
const verdict2 = passed === total ? "PASS" : "FAIL"; // same result, one line
console.log(verdict2);
⌨️ Terminal
node ternary.js
🖥️ Output
FAIL
FAIL
When an else if chain maps fixed keys to values, a lookup object is clearer and easier to extend:
A single = assigns a value, and the assigned value is then used as the condition. This compiles but is almost always a bug:
📄 assign-bug.js
let env = "qa";
if (env = "prod") { // bug: assigns "prod", which is truthy
console.log("Running against PRODUCTION!");
}
console.log("env is now:", env);
⌨️ Terminal
node assign-bug.js
🖥️ Output
Running against PRODUCTION!
env is now: prod
Fix: use ===. ESLint’s no-cond-assign rule reports this mistake.
Comparing a range incorrectly
📄 range-bug.js
const age = 40;
console.log(18 < age < 30); // (18 < 40) is true, then true < 30 -> 1 < 30
console.log(age > 18 && age < 30); // correct
⌨️ Terminal
node range-bug.js
🖥️ Output
true
false
JavaScript evaluates 18 < age < 30 left to right: the first comparison becomes true, which converts to 1, and 1 < 30 is true. Always combine two comparisons with &&.
A semicolon after the condition
if (isAdmin); { deleteUser(); } runs deleteUser() every time, because the ; ends the if with an empty statement and the block that follows is just a block. Prettier and ESLint catch this.
🧪 Tester Scenario: Classify Test Results
This function turns raw test results into a readable status, the kind of logic used in custom reporters and CI summaries:
firefox -> Gecko
webkit -> WebKit
opera -> unknown
Q6. Find and fix the bug: the code always prints Admin area.
let role = "tester";
if (role = "admin") {
console.log("Admin area");
} else {
console.log("Tester area");
}
Show answer
A single = assigns "admin" to role, and the non-empty string is truthy. Use ===:
📄 practice6.js
let role = "tester";
if (role === "admin") {
console.log("Admin area");
} else {
console.log("Tester area");
}
🖥️ Output
Tester area
🧠 MCQ Quiz: if, else if, else
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
When does the block of if (value) { ... } run?
Answer: When value is truthy. The condition is converted to a boolean using the truthy/falsy rules.
In an if / else if / else chain, how many blocks run?
Answer: At most one (exactly one if there is an else). JavaScript runs the first matching block and skips the rest.
What is printed?
const n = 95;
if (n >= 60) console.log("C");
else if (n >= 90) console.log("A");
Answer: C. The first condition matches, so the more specific check is never reached.
What does if (x = 5) do?
Answer: Assigns 5 to x and always runs the block. = assigns; the assigned value 5 is truthy.
What is 3 < 2 < 1?
Answer: true. (3 < 2) is false, false becomes 0, and 0 < 1 is true.
What is a guard clause?
Answer: An early return that handles an invalid case at the start of a function. Guard clauses reduce nesting by exiting early.
Which is the clearest way to check whether role is “admin”, “owner” or “editor”?
Answer:["admin", "owner", "editor"].includes(role). Option 2 is always truthy; option 3 checks array indexes, not values.
Why should you always use braces with if?
Answer: Adding a second line later without braces would put it outside the if. Without braces only the next single statement belongs to the if.
What runs here?
if (false); {
console.log("hi");
}
Answer: “hi” is printed. The semicolon ends the if; the block runs on its own.
When is a lookup object better than an else if chain?
Answer: When mapping fixed keys to fixed values. Lookups are clean for exact matches; ranges still need if/else if.
💼 Interview Questions and Answers
Q1. How do if/else and the ternary operator differ?
if/else is a statement: it chooses which block of code to run and can contain any number of statements. The ternary is an expression: it chooses between two values and can be used inside other expressions (assignments, template literals, return statements). Use the ternary for simple value choices and if/else for logic and side effects.
Q2. What are guard clauses and why are they useful?
Guard clauses are checks at the top of a function that return (or throw) early for invalid or special cases. They remove nesting, keep the main path at the lowest indentation level, and make each rule easy to see. In test helpers they produce clear error messages early, for example if (!baseURL) throw new Error("BASE_URL is not set").
Q3. Explain the output of this code.
📄 explain.js
const items = [];
if (items) console.log("has items?");
if (items.length) console.log("really has items");
if ("0") console.log("string zero is truthy");
⌨️ Terminal
node explain.js
🖥️ Output
has items?
string zero is truthy
An empty array is an object, so it is truthy and the first message prints. items.length is 0 (falsy), so the second does not. The string "0" is non-empty and therefore truthy.
Q4. How would you test a function with many if/else branches?
Write at least one test per branch (branch coverage), plus boundary values for each comparison: for score >= 90 test 89, 90 and 91. Include invalid inputs that guard clauses should reject (null, empty arrays, negative numbers). Table-driven tests, an array of input/expected pairs in a loop, keep this compact; Playwright and Jest both support this pattern.
Q5. How can you avoid a long if/else if chain?
A lookup object or Map for exact key-to-value mappings.
A switch statement for many exact matches with different code (next lesson).
Guard clauses for validation rules.
Polymorphism (different classes with the same method) for behaviour that varies by type, covered in the OOP module.
❓ Frequently Asked Questions
🤔 Can I write if without curly braces?
Yes, for a single statement, but it is risky because a second line added later would run unconditionally. Most style guides require braces.
🤔 Is there an elseif keyword in JavaScript?
No. JavaScript uses two words, else if. Writing elseif is a syntax error.
🤔 How many else if blocks can I use?
As many as you need, but more than three or four usually means a lookup object, a switch or guard clauses would be clearer.
🤔 What is the difference between if (x) and if (x !== undefined)?
if (x) is false for every falsy value, including 0, “” and false. if (x !== undefined) is true for those values. Use the explicit check when 0 or “” are valid.
🏁 Summary
if runs a block when its condition is truthy; else runs when it is not.
else if chains test conditions in order and run only the first match, so put specific conditions first.
Combine conditions with &&, || and !; use includes for “one of many values”.
Guard clauses with early returns replace deep nesting; ternaries and lookup objects replace simple chains.
Watch for = instead of ===, chained range comparisons and a stray semicolon after the condition.
Double-click on the exe file and initiate installation with exe , select all default options, and complete the installation.
Create a folder in C Drive with the name GithubCode, folder path should be C:\GithubCode
Open folder and right-click -> show more options -> click on open git bash here.
It will open the Git terminal in the C:\GithubCode folder.
Run a command to check the git option git –help
It will show available git commands
Steps to Add User Credentials in Git Config File
Open the Git terminal in the C:\GitHubCode folder
Run the command below to open the config file -> git config –global –edit -> It will open the config file in the vi editor
Press i to enable insert mode, it should show –insert– in the bottom.
Now use keyboard arrows and update the name and email with your git username and git email. [user] name = Divya4255 email = divya.smsrinivas1995@gmail.com
Make sure to remove # from the name and email line in the config file.
Press the ESCAPE key to disabled insert mode.
start type :wq and press enter -> It will save the configuration details.
Steps to Clone the Repository on the User’s Machine
Go to the GitHub server, log in with your credentials
Navigate to the repository that we have already created.
Click on the Code (green color) button, and copy the repository from there.
Open the Git terminal in the C:\GitHubCode folder.
Run the command below to clone the repo -> git clone https://github.com/Divya4255/AutomationPractice.git
Hit Enter -> It will clone repository from server to your local machine.
The repository folder will be created on the local machine.
Steps to Create a New File and Push to the GitHub Server
Create a text file in the git repository folder (AutomationPractice) and rename as demo_file.txt
Open the text file and add some content to the file -> save the file.
Open the Git terminal in C:\GitHubCode\AutomationPractice folder.
Run the git status command -> git status: it will show the new demo file in red color.
Run the git add command -> git add file_path/filename # It will add the file to GitHub tracking
Check the status again. -> git status # It will show the demo file in green color.
Initiate commit operation -> git commit -m “adding new file to repo.” -> It will complete the commit operation.
Initiate the git push operation. -> git push -> It will launch a pop-up -> Click and open in browser option. -> It will open in browser and click on the Authorize git ecosystem button. -> Now push will be successful and file will be push to the server. -> Check on GitHub server, the file is available on GitHub server.
Home Work For Practice:
Create three different file and push them to the server.
Update file1 and push(git status, git add, git commit, git push) it.
Rename file2 and push it from the terminal.
Delete file3 and push it from terminal.
Create a Common Repo and Provide Access
Create a repository with the name: e.g., GTM_PlaywrightTS_BATCH11
Get students’ email and provide Access to collaborate. Go to Repository -> Settings -> Collaborators -> Add People -> Enter Your email -> Select User -> Add to Repository
People will receive an invitation via email.
Open the email, click View Invitation, then accept the invitation.
Everyone has to accept the invitation.
Make sure to accept the invitation from the laptop, and your GitHub account is already open in the same browser where you open the mail account.
Once the invitation is accepted, the user will be able to see the common repository.
Clone the Common Repo, Add folder your name
Go to the common repository -> click on code (green button) -> click on copy clipboard to copy URL.
Open the Git terminal in the C:\GitHubCode folder on the local system
Run this command to clone the common repository -> git clone https://github.com/sqatools/GTM_PlaywrightTS_BATCH11.git
It will clone the command repository into a C:\GitHubCode to the local directory. -> repository folder name: GTM_PlaywrightTS_BATCH11
Create folder with your name in repo e.g. Deepesh and Add file inside the your folder e.g. first_file.txt
Navigate back to git terminal.
ON git terminal run below command to go inside repository folder. cd GTM_PlaywrightTS_BATCH11 -> It will open GTM_PlaywrightTS_BATCH11 folder.
Check status using below command -> git status : New Folder name will show in red color.
If push is rejected repeat this steps until push it not successful. -> git pull -> it will open merge editor -> we have to close the edit with command using :wq (save file) -> Once the edit is closed, re-initiate the push operation -> git push -> if push is still rejected (Repeat again from “git pull” command)
################ Multi branching in git
Go to Git Repository on server : GTM_PlaywrightTS_BATCH11
Click on repository dropdown. default is main
click on view all branches.
Create branch with your name e.g. deepesh_branch. -> New Branch -> Provide Branch Name e.g. firstname_branch -> click on create branch button -> Verify branch is created successfully.
Open git terminal in repository folder
run command to update the repo -> git pull (all newly created branches will show in the console output)
Check current active branch -> git branch : It will show main as active branch in green color.
Switch to new branch. -> git checkout deepesh_branch
check again active branch -> git branch : your branch will show as active branch in green color e.g. deepesh_branch
Go to your dedicated folder and add file inside the folder Folder Name : Deepesh Filename : deepesh_feature_file.txt (don’t add space in filename)
11 Go back to terminal and check status -> git status : newly added file will show in red color
Run git add command -> git add
Initiate commit operation -> git commit -m “added new file to feature branch”
Initiate push operation -> git push : file will push to the server on dedicated branch.
Go to GitHub server and verify file is available in dedicated folder in your branch.
################### Create pull from server
Go to server and navigate to repository.
Click on “Compare & pull request” button (green button)
Provide pull request description.
Add reviwers to review the code.
Click on create pull button.
################### Create workflow file in branch
Go to repository on GitHub server
Navigate to Actions Tab.
Click on New Workflow (green color) button
Select any workflow from given list. e.g. simple workflow
click on configure button
Select your branch from left side dropdown e.g. deepesh_branch.
Provide workflow name default name is blank.yml default path: GTM_Playwright_Batch11/.gitHub/workflow/blank.yml keep this path alive pull_request: branches: [ “main” ] remove this part: this will execute workflow for every single push push: branches: [ “main” ]
click on commit changes button.
It will open pop to provide commit message -> we can click on commit changes and push to the current branch.
It will create workflow on your dedicated branch and execute along with each PR.
########## Resolve Merge conflict
conflict scenario
Create file1 in main branch add some code from line 1 to 10.
Create new branch from main branch and then modify same file1 and same line numbers from 1 to 10.
In main branch, modify same on same number of lines and push it.
Create pull request from feature to main branch
It will create conflict.
We have to resolve conflict and merge the change
Steps to reproduce conflict scenario
Open git terminal in repository folder. -> make sure your current active branch should be main -> if not then you can switch to main branch. -> ‘git checkout main’ # it will switch to main branch. -> ‘git pull’ : Update your main branch with all change from server. -> ‘git branch’ : current active branch should be main branch in green color
Create a file with name e.g. dy_conflict_file.txt, and code snipet in the file, and save the file. var num1 = 10 if (num1%2 == 0) { console.log(“This is even number”) } else { console.log(“This is odd number”) }
Push file to main branch. -> git status: show file in read color -> git add -> git status : show file in green color -> git commit -m “added file” -> git push : It push is rejected, then pull the code and perform push operation. -> git pull : it will open editor, we have close it with :wq! command. -> then try to push again, repeat (pull, push), until it is not successful.
Create a branch from local git bash terminal. -> git checkout -b “dy_conflict_branch”
Update dy_conflict_file.txt file as given below. if (num1%2 == 0) { console.log(“This is even number, divisible by 2”) } else { console.log(“This is odd number, not divisible by 2”) }
go back to terminal and run below command -> git status : shows in red color -> git add -> git status : shows file in green color -> git commit -m “initiate commit operation”
run below command to push local branch to server -> git push –set-upstream origin dy_conflict_branch -> push will be successful in feature.
change branch from conflict branch to main branch in terminal -> git checkout main -> git pull : it will update all changes from server to local machine.
Open conflict file in your folder and update few change in file content. var num1 = 10 if (num1%2 == 0) { console.log(“condition is True”) console.log(“This is even number, can divide by 2”) } else { console.log(“condition is False”) console.log(“This is odd number, can not divide by 2”) }
push the file change in main branch. -> git status -> git add -> git commit -m “updated file” -> git push (repeat pull and push commands)
Go to GitHub server and create pull request from conflict branch to main branch -> go to repository -> search your branch name and select the branch. -> if the branch is old, then it will show contribute button -> click on contribute button and click on ‘Open pull request’ button. -> Provide request details (reviewer, description assignee) -> click on create pull request button.
It will show merge conflict between main branch and feature branch. -> ‘merge pull request’ button will be in disable state. This branch has conflicts that must be resolved Use the web editor or the command line to resolve conflicts before continuing. Deepesh/dy_conflict_file.txt
—— Resolve merge conflict locally ——
Go back to git terminal
switch to feature branch. -> git checkout dy_conflict_branch
run a command on terminal to update feature branch with main branch -> git pull origin main -> it will show conflict message on terminal Auto-merging Deepesh/dy_conflict_file.txt CONFLICT (content): Merge conflict in Deepesh/dy_conflict_file.txt Automatic merge failed; fix conflicts and then commit the result.
Open dy_conflict_file.txt on local machine, will show below content
var num1 = 10 if (num1%2 == 0) {
HEAD : change from feature BRANCH (dy_conflict_branch)
<<<<<<< HEAD console.log(“This is even number, divisible by 2”) } else {
console.log(“This is odd number, not divisible by 2”)
Changes from MAIN branch
console.log(“condition is True”) console.log(“This is even number, can divide by 2”) } else { console.log(“condition is False”) console.log(“This is odd number, can not divide by 2”)
9f9d33c6d4f9d945d512c3b40e36783b758295fd }
Update the file content as per your requirements. var num1 = 10 if (num1%2 == 0) { console.log(“condition is True”) console.log(“This is even number, divisible by 2”) } else { console.log(“condition is False”) console.log(“This is odd number, not divisible by 2”) }
go to git terminal and run below commands -> git status : It will show in red color -> git add -> git commit -m “resolved merge” -> git push
Once the push is successful, merge will conflict will be resolved in pull request -> Now go back to git server and check pull request, there is no conflict anymore.
Values often arrive as the wrong type. Text from a web page, a form field, a CSV file or a command-line argument is always a string, even when it looks like a number. JavaScript can convert types for you (coercion), but its automatic rules are a famous source of bugs such as "5" + 2 giving "52". In this lesson you will learn to convert values explicitly and safely, understand the implicit rules, and parse real UI text like "₹1,299.50" into numbers you can assert on.
📖 What You’ll Learn: explicit conversion with String(), Number(), Boolean(), parseInt() and parseFloat(), the unary plus, toString() and toFixed(), implicit coercion with +, -, * and comparisons, how null, undefined, empty strings and arrays convert, NaN and Number.isNaN, and parsing numbers and dates from text.
🔄 Conversion vs Coercion
Definition:type conversion means turning a value of one type into another type. When you do it on purpose with a function such as Number("42"), it is explicit conversion. When JavaScript does it automatically because an operator needs a different type, it is implicit conversion, also called type coercion.
📄 intro.js
const fromInput = "42"; // text from a form, a page or process.argv
const explicit = Number(fromInput); // you decide: string -> number
const implicit = fromInput * 2; // JavaScript decides: * needs numbers
console.log(explicit, typeof explicit);
console.log(implicit, typeof implicit);
console.log(fromInput + 2); // + with a string joins text instead!
⌨️ Terminal
node intro.js
🖥️ Output
42 number
84 number
422
Values can be converted to only three primitive types: string, number and boolean. Learn the rules for those three and coercion stops being surprising.
String(value) works for every value, including null and undefined.
value.toString() throws on null and undefined because they have no methods.
Plain objects become "[object Object]". Use JSON.stringify(obj) to turn an object into readable text.
🔢 Convert to Number: Number(), parseInt(), parseFloat()
Number(value) converts the whole value or returns NaN if any part is invalid. parseInt() and parseFloat() read a number from the start of a string and stop at the first invalid character.
42 3.14 12
0 NaN NaN
1 0 0 NaN
0 7 NaN
12 3.75 3
NaN 5 255
8 0 NaN
Input
Number()
parseInt()
parseFloat()
"42"
42
42
42
"3.99"
3.99
3
3.99
"12px"
NaN
12
12
""
0
NaN
NaN
null
0
NaN
NaN
true
1
NaN
NaN
⚠️ Watch out:Number("") and Number(null) return 0, not NaN. An empty form field can therefore silently become the number 0. Check for empty strings before converting user input.
💡 Tip: Always pass the radix (base) to parseInt: parseInt(value, 10). It documents your intent and avoids surprises with strings such as "0x1A", which parseInt reads as hexadecimal.
✅ Convert to Boolean
Boolean(value) (or !!value) converts using a short list of falsy values. Everything not on the list is truthy.
The falsy values are false, 0, -0, 0n, "", null, undefined and NaN. Note that the strings "0" and "false", empty arrays and empty objects are all truthy. The next lessons use this in conditions.
⚠️ Implicit Coercion with Operators
Operators coerce their operands. The rules that matter most:
+: if either side is a string, both are converted to strings and joined. Otherwise both become numbers.
-, *, /, %, **: always convert both sides to numbers.
Comparisons <>: convert to numbers, unless both sides are strings, which are compared alphabetically.
⚠️ Watch out: Sorting or comparing numbers that are stored as strings gives alphabetical results: "10" < "9" because "1" comes before "9". Convert to numbers before comparing prices, counts or IDs read from a page.
🚫 NaN: Not a Number
Definition:NaN is a special number value that means “the result is not a valid number”. It appears when a conversion or calculation fails. NaN is the only value that is not equal to itself, so value === NaN never works.
📄 nan.js
const qty = Number("two");
console.log(qty, typeof qty);
console.log(qty === NaN); // always false!
console.log(Number.isNaN(qty)); // correct check
console.log(isNaN("hello")); // global isNaN converts first -> true
console.log(Number.isNaN("hello")); // only true for the NaN value itself -> false
console.log(Number.isFinite(Number("1e3")), Number.isFinite(Infinity));
⌨️ Terminal
node nan.js
🖥️ Output
NaN number
false
true
true
false
true false
💡 Tip: To validate that text is a usable number, convert it and check Number.isFinite(n). It rejects NaN, Infinity and -Infinity in one call.
🧪 Tester Scenario: Parse Prices and Counts from UI Text
A page shows "₹1,299.50", "Showing 25 of 1,024 results" or "$0.99". To assert on these values, remove everything except digits, the decimal point and the minus sign, then convert:
📄 parse-ui.js
function parsePrice(text) {
const cleaned = text.replace(/[^0-9.-]/g, ""); // keep digits, dot and minus
if (cleaned === "") throw new Error(`No number in "${text}"`);
const value = Number(cleaned);
if (!Number.isFinite(value)) throw new Error(`Invalid price "${text}"`);
return value;
}
const cartLines = ["₹1,299.50", "₹ 450.00", "₹50"];
const total = cartLines.map(parsePrice).reduce((sum, p) => sum + p, 0);
console.log("Line prices:", cartLines.map(parsePrice));
console.log("Total:", total.toFixed(2));
const summary = "Showing 25 of 1,024 results";
const [shown, all] = summary.match(/[\d,]+/g).map((s) => parseInt(s.replace(/,/g, ""), 10));
console.log({ shown, all });
replace(/[^0-9.-]/g, "") uses a regular expression to delete currency symbols, commas and spaces (Module 5 explains regular expressions).
The function throws a clear error for text without a number, so a broken page fails the test instead of comparing NaN.
match(/[\d,]+/g) finds every group of digits and commas in the sentence.
⚠️ Watch out: This simple cleaner assumes “.” is the decimal separator. Pages in locales that write 1.299,50 need a locale-aware parser or a fixed test locale (Playwright’s locale option).
📅 Bonus: Dates and JSON Conversion
Two more conversions you will use all the time in tests:
📄 dates-json.js
// Dates <-> numbers and strings
const d = new Date("2026-11-23T10:30:00Z");
console.log(d.getTime()); // milliseconds since 1 Jan 1970 (UTC)
console.log(d.toISOString()); // standard string for APIs
console.log(new Date(0).toISOString());
// Objects <-> JSON text
const payload = { id: 7, tags: ["smoke"], active: true };
const text = JSON.stringify(payload);
console.log(text, typeof text);
const back = JSON.parse(text);
console.log(back.tags[0], typeof back);
API responses arrive as JSON text and are converted with JSON.parse (Playwright’s response.json() does this for you). The JSON lesson in Module 7 goes further.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Convert "19.99", "5" and "0.01" to numbers and print their sum with two decimals.
Show answer
📄 practice1.js
const prices = ["19.99", "5", "0.01"];
const sum = prices.map(Number).reduce((a, b) => a + b, 0);
console.log(sum.toFixed(2));
🖥️ Output
25.00
Q2. Predict each result before running: "3" + 4 + 5, 3 + 4 + "5", "3" * "4", "10" - "4" + "1".
Evaluation goes left to right. "3" + 4 is already a string, so 5 is appended. 3 + 4 is 7 before meeting the string. "10" - "4" is the number 6, then + "1" joins text.
Q3. Write toQuantity(text) that returns a whole number from input such as " 3 ", and throws an error for "", "abc" or "2.5".
Show answer
📄 practice3.js
function toQuantity(text) {
const trimmed = String(text).trim();
const n = Number(trimmed);
if (trimmed === "" || !Number.isInteger(n)) {
throw new Error(`Invalid quantity: "${text}"`);
}
return n;
}
console.log(toQuantity(" 3 "));
for (const bad of ["", "abc", "2.5"]) {
try {
toQuantity(bad);
} catch (e) {
console.log(e.message);
}
}
The empty-string check is needed because Number("") is 0, a valid integer.
Q4. An array of order IDs read from a table is ["10", "9", "100", "25"]. Sort it numerically from smallest to largest.
Show answer
📄 practice4.js
const ids = ["10", "9", "100", "25"];
console.log([...ids].sort()); // alphabetical: wrong
console.log(ids.map(Number).sort((a, b) => a - b)); // numeric: right
🖥️ Output
[ '10', '100', '25', '9' ]
[ 9, 10, 25, 100 ]
Q5. Print the boolean value of "0", 0, "false", [] and "" using !!.
Show answer
📄 practice5.js
for (const v of ["0", 0, "false", [], ""]) {
console.log(JSON.stringify(v), !!v);
}
🖥️ Output
"0" true
0 false
"false" true
[] true
"" false
Q6. Extract the rating number from "Rated 4.5 out of 5 (1,203 reviews)" as a number, and the review count as a whole number.
Show answer
📄 practice6.js
const text = "Rated 4.5 out of 5 (1,203 reviews)";
const rating = parseFloat(text.match(/[\d.]+/)[0]);
const reviews = parseInt(text.match(/\(([\d,]+)/)[1].replace(/,/g, ""), 10);
console.log(rating, reviews, typeof rating, typeof reviews);
🖥️ Output
4.5 1203 number number
🧠 MCQ Quiz: Type Conversion and Coercion
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
What is "5" + 2?
Answer:"52". With + and a string operand, both sides are joined as strings.
What is "5" - 2?
Answer:3. The minus operator always converts both sides to numbers.
What does Number("") return?
Answer:0. An empty (or whitespace-only) string converts to 0, a common bug with empty inputs.
What does parseInt("12px", 10) return?
Answer:12. parseInt reads digits from the start and stops at “p”. Number("12px") would be NaN.
Which check correctly detects NaN?
Answer:Number.isNaN(x). NaN is not equal to anything, including itself.
Which of these is truthy?
Answer:"0". Any non-empty string is truthy, even “0” and “false”.
What is "10" > "9"?
Answer:false. Two strings are compared character by character, and “1” comes before “9”.
What does (7.456).toFixed(2) return?
Answer: The string "7.46". toFixed rounds and returns a string; wrap it in Number() if you need a number.
What is null + 1?
Answer:1. null converts to 0 in arithmetic; undefined converts to NaN.
Why should you pass 10 as the second argument to parseInt?
Answer: It states the base explicitly and avoids reading strings like “0x1A” as hexadecimal. The radix tells parseInt which number base to use.
💼 Interview Questions and Answers
Q1. What is the difference between type conversion and type coercion?
Conversion is explicit: you call Number(), String(), Boolean(), parseInt() and so on. Coercion is implicit: the engine converts automatically because an operator or context needs another type, for example "5" * 2, if (value) or "a" + 1. Coercion only ever produces strings, numbers or booleans.
Q2. What is the difference between Number(), parseInt() and parseFloat()?
Number() converts the entire value and returns NaN if anything is invalid (Number("12px") is NaN), and treats "", null and false as 0. parseInt(str, radix) parses an integer from the beginning of a string and stops at the first invalid character. parseFloat() does the same but keeps decimals. Use Number() for strict validation and the parse functions for strings with units.
[] + {}: both convert to strings, "" and "[object Object]".
1 + "2" is "12", then - 1 converts back to a number: 11.
true + true: booleans become 1 + 1 = 2.
+"a" is NaN, which is joined as text, giving "baNaNa".
Q4. How do you safely read a number from text on a web page in a test?
Get the text (for example await locator.textContent()) and trim it.
Remove formatting such as currency symbols, thousands separators and units with a regular expression.
Convert with Number() and validate with Number.isFinite(); throw a clear error if it fails.
Compare with a tolerance for decimals, or compare integer cents, to avoid floating-point issues.
Fix the test locale so number formatting is predictable.
Q5. Why is isNaN() considered unreliable?
The global isNaN(x) first converts x to a number, so isNaN("hello") is true even though "hello" is a string, not the NaN value. Number.isNaN(x) does not convert and returns true only for NaN itself. For input validation, Number.isFinite(Number(x)) is usually what you want.
❓ Frequently Asked Questions
🤔 How do I convert a string to a number in JavaScript?
Use Number(str) when the whole string must be a number, or parseInt(str, 10) / parseFloat(str) when it starts with a number followed by other text, such as "12px". Check the result with Number.isFinite().
🤔 How do I convert a number to a string?
Use String(n), n.toString() or a template literal `${n}`. Use n.toFixed(2) for a fixed number of decimal places.
🤔 Why does “1” + 1 equal “11”?
When either side of + is a string, JavaScript converts the other side to a string and joins them. Convert the string first: Number("1") + 1 is 2.
🤔 Is it bad to rely on type coercion?
Coercion in conditions (if (items.length)) is normal and readable. Coercion in arithmetic and equality (==) causes bugs, so convert explicitly and use ===.
Every value in JavaScript has a type: "Asha" is a string, 42 is a number, true is a boolean. The type decides what you can do with a value and how it behaves when you copy or compare it. In this lesson you will learn all eight JavaScript data types, how to check a type with typeof (and its traps), and the difference between primitive and reference values that causes so many test-data bugs.
📖 What You’ll Learn: the seven primitive types (string, number, bigint, boolean, undefined, null, symbol), the object type and its kinds (arrays, functions, dates), the typeof operator and its quirks, Array.isArray, null versus undefined, immutability of primitives, and copying by value versus by reference.
🧬 What Is a Data Type?
Definition: a data type describes what kind of value something is and which operations make sense for it. JavaScript has 8 data types: seven primitive types and one object type.
Type
Example
Used for
string
"Asha", 'QA', `hi`
Text
number
42, 3.14, -7, NaN
Integers and decimals
bigint
9007199254740993n
Whole numbers larger than 253
boolean
true, false
Yes/no conditions
undefined
undefined
A value that was never set
null
null
An intentionally empty value
symbol
Symbol("id")
Unique keys
object
{}, [], functions, dates
Collections and complex data
Because JavaScript is dynamically typed, a variable has no fixed type; the value has the type.
🔤 The Primitive Types
Definition: a primitive is a simple value that is not an object and has no properties of its own. Primitives are immutable: you cannot change a primitive value, you can only replace it with another.
📄 primitives.js
const name = "Asha"; // string
const age = 29; // number (integers and decimals share one type)
const price = 499.99; // number
const views = 12345678901234567890n; // bigint (note the n)
const isActive = true; // boolean
let nickname; // undefined (declared, not assigned)
const middleName = null; // null (deliberately empty)
const id = Symbol("id"); // symbol
console.log(typeof name, typeof age, typeof price);
console.log(typeof views, typeof isActive, typeof nickname);
console.log(typeof middleName, typeof id);
⌨️ Terminal
node primitives.js
🖥️ Output
string number number
bigint boolean undefined
object symbol
string: text in double quotes, single quotes or back-ticks. Back-ticks allow ${...} placeholders.
number: one type for integers and decimals, plus the special values Infinity, -Infinity and NaN (“not a number”).
bigint: integers of any size, written with an n suffix. Covered in the Numbers lesson.
symbol: every Symbol() is unique, even with the same description. Libraries use symbols for hidden property keys.
Strings look like they have methods, and they do, but calling a method never changes the original string:
📄 immutable.js
let status = "passed";
const upper = status.toUpperCase();
console.log(status, upper); // the original is unchanged
status[0] = "P"; // ignored: strings are immutable
console.log(status);
console.log(Symbol("id") === Symbol("id")); // every symbol is unique
⌨️ Terminal
node immutable.js
🖥️ Output
passed PASSED
passed
false
🗂️ The Object Type: Objects, Arrays, Functions and More
Definition: an object is a collection of properties (key–value pairs). Everything that is not a primitive is an object, including arrays, functions, dates, maps and regular expressions.
"text" -> string
7 -> number
NaN -> number
5n -> bigint
true -> boolean
undefined -> undefined
null -> null
[1] -> array
{ a: 1 } -> object
new Date() -> date
() => {} -> function
💡 Tip: To check for null reliably, compare directly: value === null. Never rely on typeof value === "object" alone, because null passes that check too.
🕳️ undefined vs null
Both mean “no value”, but they are used differently:
undefined
null
Meaning
Not set yet / missing
Deliberately empty
Who sets it
Usually JavaScript itself
Usually you (or an API)
Where you see it
Unassigned variables, missing properties, functions with no return, missing arguments
API fields with no value, “clear this field”
typeof
"undefined"
"object"
In JSON
Omitted from the output
Kept as null
📄 null-undefined.js
const order = { id: 101, coupon: null };
let shippedAt;
function log() {}
console.log(shippedAt); // never assigned
console.log(order.trackingNo); // property does not exist
console.log(log()); // function with no return value
console.log(order.coupon); // explicitly empty
console.log(JSON.stringify({ a: undefined, b: null }));
console.log(null == undefined, null === undefined);
The last line previews the next lessons: loose equality == treats null and undefined as equal, strict equality === does not.
📋 Copy by Value vs Copy by Reference
This is the most important difference between primitives and objects, and a frequent source of test bugs.
Primitives are copied by value. The new variable gets its own copy.
Objects are copied by reference. The new variable points to the same object, so a change through one name is visible through the other.
📄 reference.js
let a = 10;
let b = a; // copy of the value
b = 20;
console.log("primitives:", a, b);
const original = { user: "asha", role: "tester" };
const copy = original; // copy of the reference (same object)
copy.role = "admin";
console.log("objects:", original.role, copy.role);
console.log("same object?", original === copy);
⌨️ Terminal
node reference.js
🖥️ Output
primitives: 10 20
objects: admin admin
same object? true
To get an independent copy of an object, create a new one. structuredClone() makes a deep copy, including nested objects:
📄 clone.js
const baseUser = { name: "asha", address: { city: "Pune" } };
const shallow = { ...baseUser }; // new top-level object
const deep = structuredClone(baseUser); // new object at every level
shallow.name = "ravi";
shallow.address.city = "Delhi"; // nested object is still shared!
deep.address.city = "Mumbai";
console.log(baseUser);
console.log(deep);
⚠️ Watch out: A common flaky-test pattern: a shared test-data object is modified by one test, and the next test receives the changed data. Build fresh data for each test, or clone a template with structuredClone().
The same rule applies to comparison: two objects are equal only if they are the same object.
📄 compare.js
console.log({ id: 1 } === { id: 1 }); // two different objects
console.log([1, 2] === [1, 2]);
const x = { id: 1 };
const y = x;
console.log(x === y); // same reference
⌨️ Terminal
node compare.js
🖥️ Output
false
false
true
🧪 Tester Scenario: Validate the Types in an API Response
API tests often check that each field has the right type, not just the right value. This example validates a user object against a simple schema:
📄 schema-check.js
const response = {
id: 42,
email: "qa@sqatools.in",
active: true,
roles: ["tester"],
manager: null,
createdAt: "2026-11-23T10:00:00Z",
};
const schema = {
id: "number",
email: "string",
active: "boolean",
roles: "array",
manager: "null",
createdAt: "string",
};
function typeName(v) {
if (v === null) return "null";
if (Array.isArray(v)) return "array";
return typeof v;
}
let errors = 0;
for (const field in schema) {
const actual = typeName(response[field]);
const ok = actual === schema[field];
if (!ok) errors++;
console.log(`${ok ? "PASS" : "FAIL"} ${field}: expected ${schema[field]}, got ${actual}`);
}
console.log(errors === 0 ? "Schema check passed" : `${errors} field(s) failed`);
saved and cart are the same object, so both show 5. count received a copy of the number 5, so changing it to 10 does not affect the object.
Q4. Create a test-data template { name: "asha", tags: ["ui"] }. Make an independent copy, add "api" to the copy’s tags, and show that the template did not change.
A spread copy { ...template } would share the same tags array, so the template would change too.
Q5. Which of these values are primitives: "abc", null, [], Symbol(), new Date(), 0n, function(){}?
Show answer
Primitives: "abc", null, Symbol(), 0n. Objects: [], new Date(), function(){}.
Q6. An API returns { discount: null } for one product and {} for another. Write code that prints no discount field, discount is empty or the discount value for each case.
Show answer
📄 practice6.js
function describe(product) {
if (product.discount === undefined) return "no discount field";
if (product.discount === null) return "discount is empty";
return `discount ${product.discount}%`;
}
console.log(describe({ discount: null }));
console.log(describe({}));
console.log(describe({ discount: 15 }));
🖥️ Output
discount is empty
no discount field
discount 15%
🧠 MCQ Quiz: Data Types
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
How many data types does JavaScript have?
Answer: 8 (7 primitives and object). string, number, bigint, boolean, undefined, null, symbol and object.
What is typeof null?
Answer:"object". A bug from the first JavaScript version that cannot be fixed without breaking the web.
What is typeof [1, 2, 3]?
Answer:"object". Arrays are objects; use Array.isArray() to detect them.
What is typeof NaN?
Answer:"number". NaN (“not a number”) is a special value of the number type.
Which value is not a primitive?
Answer:[]. Arrays are objects.
After const a = { n: 1 }; const b = a; b.n = 2;, what is a.n?
Answer: 2. Both names refer to the same object.
What does { id: 1 } === { id: 1 } return?
Answer:false. Objects are compared by reference, and these are two separate objects.
What does JSON.stringify({ a: undefined, b: null }) return?
Answer:'{"b":null}'. Properties with undefined are left out of JSON; null is kept.
Which creates an independent deep copy of an object?
Answer:structuredClone(obj). Spread copies only the top level; nested objects remain shared.
What is the result of Symbol("id") === Symbol("id")?
Answer:false. Every symbol is unique, whatever its description.
💼 Interview Questions and Answers
Q1. List the JavaScript data types and say which are primitives.
There are eight: string, number, bigint, boolean, undefined, null and symbol are primitives; object covers everything else, including arrays, functions, dates, maps, sets and regular expressions. Primitives are immutable and compared by value; objects are mutable and compared by reference.
Q2. What is the difference between null and undefined?
undefined means a value was never assigned: unassigned variables, missing properties, missing arguments and functions without return. null is an explicit “no value” that a developer or API sets on purpose. typeof undefined is "undefined" while typeof null is "object"; null == undefined is true but null === undefined is false; JSON keeps null but drops undefined properties.
Q3. How do you reliably check whether a value is an array, an object or null?
For more precise names, Object.prototype.toString.call(v) returns strings such as "[object Date]".
Q4. Explain pass-by-value and pass-by-reference in JavaScript.
JavaScript always passes arguments by value, but for objects the value is a reference. So a function that changes a property of an object argument changes the caller’s object, while reassigning the parameter to a new object does not affect the caller. Primitives are copied, so changes inside the function never leak out.
📄 pass.js
function update(user, count) {
user.name = "changed"; // visible to the caller
user = { name: "new" }; // only changes the local parameter
count = 99; // only changes the local copy
}
const u = { name: "asha" };
let c = 1;
update(u, c);
console.log(u.name, c);
⌨️ Terminal
node pass.js
🖥️ Output
changed 1
Q5. What is the difference between a shallow and a deep copy?
A shallow copy ({ ...obj }, Object.assign({}, obj), [...arr]) creates a new top-level container but nested objects are still shared. A deep copy (structuredClone(obj)) duplicates every level. JSON.parse(JSON.stringify(obj)) is an older deep-copy trick that loses undefined, functions, dates (they become strings), Map and Set.
❓ Frequently Asked Questions
🤔 Is an array a data type in JavaScript?
Not a separate one. Arrays are a kind of object, which is why typeof [] is "object". Use Array.isArray() to detect them.
🤔 Why is typeof null “object”?
In the first implementation of JavaScript, values were stored with a type tag, and the tag for objects was 0. null was represented as a null pointer, also 0, so it was reported as an object. Fixing it would break existing websites.
🤔 Does JavaScript have an integer type?
Regular numbers are all 64-bit floating point, used for both integers and decimals. For integers larger than 253 − 1, use bigint.
🤔 When should I use null instead of undefined?
Use null when you deliberately set “no value”, for example to clear a field or to send an empty value in JSON. Let undefined mean “not set”.
🏁 Summary
JavaScript has 8 data types: 7 primitives (string, number, bigint, boolean, undefined, null, symbol) and object.
typeof returns the type name, but reports null and arrays as "object"; use === null and Array.isArray().
undefined means “not set”; null means “deliberately empty”.
Primitives are immutable and copied by value; objects are mutable and copied and compared by reference.
Use structuredClone() for independent deep copies of test data.
Operators are the verbs of a programming language: they add prices, compare a status code with 200, combine conditions and pick between two values. You have already met a few; in this lesson you will learn every JavaScript operator you need in real code and tests, how short-circuit evaluation works, how i++ differs from ++i, and how precedence decides what runs first.
📖 What You’ll Learn: arithmetic operators including % and **, increment and decrement, assignment and compound assignment, comparison operators, logical operators and short-circuiting, the conditional (ternary) operator, typeof, instanceof, in, delete, spread, the comma operator, and operator precedence.
➕ Arithmetic Operators
Definition: an operator is a symbol that performs an operation on one or more values, called operands. a + b has two operands (a binary operator); -a has one (a unary operator).
📄 arithmetic.js
const a = 17, b = 5;
console.log("a + b =", a + b);
console.log("a - b =", a - b);
console.log("a * b =", a * b);
console.log("a / b =", a / b); // always a decimal division
console.log("a % b =", a % b); // remainder
console.log("a ** 2 =", a ** 2); // exponent (power)
console.log("-a =", -a); // unary minus
⌨️ Terminal
node arithmetic.js
🖥️ Output
a + b = 22
a - b = 12
a * b = 85
a / b = 3.4
a % b = 2
a ** 2 = 289
-a = -17
/ never rounds: 17 / 5 is 3.4. Use Math.floor(a / b) or Math.trunc for whole-number division.
% (remainder) is handy for even/odd checks (n % 2 === 0) and for cycling through values.
const status = 201;
const responseMs = 850;
const limitMs = 1000;
console.log("success:", status >= 200 && status < 300);
console.log("fast enough:", responseMs <= limitMs);
console.log("created:", status === 201);
console.log("not an error:", status !== 500);
⌨️ Terminal
node comparison.js
🖥️ Output
success: true
fast enough: true
created: true
not an error: true
🧠 Logical Operators and Short-Circuiting
Operator
Name
Result
a && b
AND
If a is falsy, returns a; otherwise returns b
a || b
OR
If a is truthy, returns a; otherwise returns b
!a
NOT
true if a is falsy, otherwise false
a ?? b
Nullish coalescing
b only if a is null/undefined
With booleans they work as you expect. Note that && and || return one of the operand values, not necessarily true or false:
📄 logical.js
const isLoggedIn = true;
const isAdmin = false;
console.log(isLoggedIn && isAdmin); // false
console.log(isLoggedIn || isAdmin); // true
console.log(!isAdmin); // true
console.log("Asha" && "admin"); // both truthy: returns the second value
console.log("" || "default name"); // first is falsy: returns the second
console.log(0 && "never checked"); // first is falsy: returns 0
⌨️ Terminal
node logical.js
🖥️ Output
false
true
true
admin
default name
0
Short-circuit evaluation: JavaScript stops evaluating as soon as the result is known. The right side of && runs only if the left is truthy; the right side of || runs only if the left is falsy.
📄 short-circuit.js
function sendReport() {
console.log("report sent");
return true;
}
const failures = 0;
failures > 0 && sendReport(); // left is false: sendReport never runs
failures === 0 || sendReport(); // left is true: sendReport never runs
console.log("done, no report needed");
const user = null;
console.log(user && user.name); // safe: stops at null
⌨️ Terminal
node short-circuit.js
🖥️ Output
done, no report needed
null
⚠️ Watch out: Do not use && as a hidden if in team code (isValid && save()); a real if statement is easier to read and debug. Use the operators for conditions and defaults.
❓ The Conditional (Ternary) Operator
Definition: the conditional operatorcondition ? valueIfTrue : valueIfFalse is the only operator with three operands, so it is often called the ternary operator. It is an expression, so it produces a value you can store or print.
📄 ternary.js
const score = 72;
const result = score >= 60 ? "PASS" : "FAIL";
console.log(`Score ${score}: ${result}`);
const items = 1;
console.log(`${items} ${items === 1 ? "item" : "items"} in cart`);
const ms = 1530;
const label = ms < 500 ? "fast" : ms < 1000 ? "ok" : "slow"; // chained
console.log(`${ms} ms is ${label}`);
⌨️ Terminal
node ternary.js
🖥️ Output
Score 72: PASS
1 item in cart
1530 ms is slow
💡 Tip: One level of ternary is readable; chained ternaries quickly become hard to follow. For three or more branches, use if...else if (next lesson) or a lookup object.
🔎 typeof, instanceof, in and delete
📄 keyword-ops.js
class LoginPage {}
const page = new LoginPage();
const user = { name: "Asha", role: "tester" };
console.log(typeof user.name); // type of a value
console.log(page instanceof LoginPage); // created by this class?
console.log([] instanceof Array);
console.log("role" in user, "email" in user); // does the property exist?
console.log(0 in ["a"], 1 in ["a"]); // index exists in array?
delete user.role; // remove a property
console.log(user);
typeof returns a type name as a string (covered in the Data Types lesson).
instanceof checks whether an object was created by a class or constructor.
in checks whether a property name (or array index) exists, even if its value is undefined.
delete removes a property from an object. It does not work on variables.
🌊 Spread (…) and the Comma Operator
The spread syntax ... expands an array or object into individual elements. You will use it constantly; the Destructuring and Spread lesson covers it fully.
The comma operator evaluates several expressions and returns the last one. You will mostly see it in for loops that update two variables:
📄 comma.js
for (let i = 0, j = 4; i < j; i++, j--) {
console.log(i, j);
}
⌨️ Terminal
node comma.js
🖥️ Output
0 4
1 3
📐 Operator Precedence
Definition:precedence decides which operator runs first when an expression has several. Higher precedence runs first; operators with the same precedence run left to right (except ** and assignment, which run right to left).
let x = 3;
const y = x++ + ++x;
console.log(x, y);
Show answer
📄 practice2.js
let x = 3;
const y = x++ + ++x;
console.log(x, y);
🖥️ Output
5 8
x++ returns 3 and makes x 4; ++x then makes x 5 and returns 5. So y = 3 + 5 = 8 and x is 5.
Q3. Use the remainder operator to print Fizz for multiples of 3 between 1 and 10, and the number otherwise.
Show answer
📄 practice3.js
for (let n = 1; n <= 10; n++) {
console.log(n % 3 === 0 ? "Fizz" : n);
}
🖥️ Output
1
2
Fizz
4
5
Fizz
7
8
Fizz
10
Q4. A test passes if the status is 200 and the response time is under 2000 ms, or if the status is 304. Write the condition and test it with (200, 1500), (200, 2500) and (304, 3000).
The parentheses are not strictly needed (&& has higher precedence than ||) but make the intent clear.
Q5. Use a ternary to print 1 test failed or N tests failed for 1 and 4 failures.
Show answer
📄 practice5.js
for (const failed of [1, 4]) {
console.log(`${failed} ${failed === 1 ? "test" : "tests"} failed`);
}
🖥️ Output
1 test failed
4 tests failed
Q6. Check whether the object { id: 7, email: undefined } has an email property and a phone property, using in. Then explain why user.email !== undefined gives a different answer.
Show answer
📄 practice6.js
const user = { id: 7, email: undefined };
console.log("email" in user, "phone" in user);
console.log(user.email !== undefined);
🖥️ Output
true false
false
in checks whether the property exists. email exists but holds undefined, so comparing its value says “no value”, while in says “the key is there”.
🧠 MCQ Quiz: Operators
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
Which operator checks if a property name exists in an object?
Answer:in. "key" in obj returns true even if the value is undefined.
What does score >= 50 ? "pass" : "fail" return when score is 50?
Answer:"pass". 50 >= 50 is true, so the first value is returned.
💼 Interview Questions and Answers
Q1. What is the difference between x++ and ++x?
Both add 1 to x. Postfix x++ evaluates to the value before the increment; prefix ++x evaluates to the value after. The difference only matters when the expression’s value is used, for example const y = x++. As a standalone statement they are identical.
Q2. What is short-circuit evaluation, and how is it used?
&& stops at the first falsy operand and || stops at the first truthy operand, without evaluating the rest. It is used for guards (user && user.name), defaults (name || "guest", better ?? when 0 or “” are valid), and to avoid unnecessary work. It also means function calls on the right side may never run, which matters if they have side effects.
Q3. Do && and || always return booleans?
No. They return one of their operands. "a" && 0 returns 0; null || "x" returns "x". Only ! always returns a boolean. Use Boolean(a && b) or !!(a && b) when you need a real boolean, for example for an API flag.
Q4. When would you use the ternary operator instead of if/else?
When choosing between two values in an expression: a label, a plural form, a default inside a template literal or JSX. Use if/else when you need to run statements (several lines, side effects) or when there are more than two branches. Nested ternaries hurt readability and are often blocked by lint rules.
Q5. What is operator precedence and associativity? Give an example where it causes a bug.
Precedence decides which operator binds first; associativity decides the order for operators of equal precedence. A common bug: "Total: " + price + tax joins strings left to right, giving "Total: 10020" instead of "Total: 120". Grouping fixes it: "Total: " + (price + tax), or use a template literal `Total: ${price + tax}`.
A variable is a named box that holds a value, such as a user name, a price or the number of failed tests. Every program you write, and every Playwright test, uses variables. In this lesson you will learn how to create variables with let, const and the older var, how scope and hoisting work, why var causes bugs, and the simple rule professionals follow to choose between them.
📖 What You’ll Learn: declaring, assigning and initialising variables, let versus const versus var, block and function scope, redeclaration, hoisting and the temporal dead zone, the classic var-in-a-loop bug, global variables and globalThis, naming rules and best practices.
📦 What Is a Variable?
Definition: a variable is a name that refers to a value stored in memory. You declare a variable to create the name, assign a value with =, and can then read the value by using the name.
📄 variables.js
let userName; // declaration: the variable exists, value is undefined
console.log(userName);
userName = "Asha"; // assignment
console.log(userName);
let attempts = 3; // declaration + initialisation in one step
console.log(`${userName} has ${attempts} attempts left`);
⌨️ Terminal
node variables.js
🖥️ Output
undefined
Asha
Asha has 3 attempts left
A declared variable that has not been given a value holds undefined.
= means “store this value”. It does not mean “equals”; comparison uses ===.
Giving a value at declaration time is called initialisation, and is the usual style.
🔑 let, const and var
JavaScript has three keywords for declaring variables:
https://sqatools.in
/home/you/js-course/const.js:4
BASE_URL = "https://example.com";
^
TypeError: Assignment to constant variable.
at Object.<anonymous> (/home/you/js-course/const.js:4:10)
Node.js v26.13.0
⚠️ Watch out:const does not make objects and arrays read-only. It only stops you from assigning a new value to the name. You can still change what is inside:
📄 const-object.js
const user = { name: "Asha", role: "tester" };
user.role = "lead"; // allowed: changing a property
console.log(user);
const tags = ["smoke"];
tags.push("regression"); // allowed: changing the array
console.log(tags);
To make an object truly read-only, use Object.freeze(), covered in the Object Methods lesson.
🧱 Scope: Block Scope vs Function Scope
Definition: the scope of a variable is the part of the code where the name can be used. let and const are block-scoped: they exist only inside the nearest { }. var is function-scoped: it ignores blocks such as if and for and belongs to the whole function.
📄 scope.js
function checkStatus(code) {
if (code === 200) {
var viaVar = "passed (var)";
let viaLet = "passed (let)";
}
console.log(viaVar); // var leaks out of the if block
console.log(typeof viaLet); // let does not exist here
}
checkStatus(200);
⌨️ Terminal
node scope.js
🖥️ Output
passed (var)
undefined
Using the block-scoped variable outside its block is an error:
📄 block.js
if (true) {
let message = "inside";
}
console.log(message);
⌨️ Terminal
node block.js
🖥️ Output
/home/you/js-course/block.js:4
console.log(message);
^
ReferenceError: message is not defined
at Object.<anonymous> (/home/you/js-course/block.js:4:13)
Node.js v26.13.0
💡 Tip: Block scope is a feature, not a limitation. Variables that live only as long as they are needed cannot be changed by accident somewhere else in the program.
♻️ Redeclaration
var lets you declare the same name twice, which can silently overwrite a value you still need. let and const refuse:
📄 redeclare-var.js
var env = "qa";
var env = "prod"; // allowed with var: the first value is lost
console.log(env);
⌨️ Terminal
node redeclare-var.js
🖥️ Output
prod
📄 redeclare-let.js
let env = "qa";
let env = "prod";
console.log(env);
⌨️ Terminal
node redeclare-let.js
🖥️ Output
/home/you/js-course/redeclare-let.js:2
let env = "prod";
^
SyntaxError: Identifier 'env' has already been declared
Node.js v26.13.0
Because this is a SyntaxError, the file does not run at all. You find the mistake immediately instead of debugging a wrong value later.
⏳ Hoisting and the Temporal Dead Zone (TDZ)
Definition:hoisting means that JavaScript registers every declaration in a scope before running any code in it. var variables are created and set to undefined at that moment. let and const are created but stay uninitialised until their declaration line runs. The period before that line is the temporal dead zone (TDZ).
📄 hoist-var.js
console.log(total); // var is hoisted with the value undefined
var total = 100;
console.log(total);
⌨️ Terminal
node hoist-var.js
🖥️ Output
undefined
100
📄 tdz.js
console.log(count); // let is in the temporal dead zone here
let count = 5;
⌨️ Terminal
node tdz.js
🖥️ Output
/home/you/js-course/tdz.js:1
console.log(count); // let is in the temporal dead zone here
^
ReferenceError: Cannot access 'count' before initialization
at Object.<anonymous> (/home/you/js-course/tdz.js:1:13)
Node.js v26.13.0
The error message is precise: the variable exists (so it is not “not defined”), but you cannot access it yet. This catches order-of-code bugs that var would hide behind an undefined.
🔁 The Classic var-in-a-Loop Bug
This bug appears in interviews and in real code that schedules work in a loop. With var there is only onei for the whole loop, so every callback sees its final value:
📄 loop-var.js
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log("var i =", i), 0);
}
⌨️ Terminal
node loop-var.js
🖥️ Output
var i = 3
var i = 3
var i = 3
With let, every loop iteration gets its own copy of i:
📄 loop-let.js
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log("let i =", i), 0);
}
⌨️ Terminal
node loop-let.js
🖥️ Output
let i = 0
let i = 1
let i = 2
setTimeout(fn, 0) runs fn after the loop has finished (you will learn why in the Event Loop lesson).
By then the single var i has become 3; the three let i bindings still hold 0, 1 and 2.
🌍 Global Variables and globalThis
A variable declared outside every function and block is global to its file. Where it ends up depends on how the file is loaded:
In a classic browser <script>, top-level var becomes a property of window; top-level let/const are global but not on window.
In Node.js and in ES modules, each file has its own scope, so top-level variables are not shared with other files.
globalThis is the standard name for the global object everywhere (window in browsers, global in Node.js).
📄 globals.js
var appName = "sqatools";
let version = 2;
console.log(appName, version); // usable in this file
console.log(globalThis.appName); // undefined: Node.js files have their own scope
console.log(typeof globalThis.setTimeout); // built-in globals live on globalThis
⌨️ Terminal
node globals.js
🖥️ Output
sqatools 2
undefined
function
⚠️ Watch out: Avoid global variables for test data. Tests that share and change globals affect each other and fail randomly when run in parallel. Pass values as function arguments or use test fixtures instead.
🏷️ Naming Rules and Best Practices
Names may contain letters, digits, _ and $, must not start with a digit and must not be reserved words (see the Syntax lesson).
Use camelCase: orderTotal, isLoggedIn.
Use UPPER_SNAKE_CASE for fixed configuration values: MAX_RETRIES, BASE_URL.
Choose descriptive names: retryCount beats rc or x.
The rule professionals use
Use const by default.
Switch to let only when the variable must be reassigned (counters, totals, values that change in a loop).
Do not use var in new code. You still need to understand it, because you will meet it in older code and interviews.
📄 retry.js
// Test configuration and a retry loop written with the rule above
const MAX_RETRIES = 3;
const endpoint = "/api/orders";
let attempt = 0;
let success = false;
while (!success && attempt < MAX_RETRIES) {
attempt++;
success = attempt === 2; // pretend the second attempt succeeds
console.log(`Attempt ${attempt} on ${endpoint}: ${success ? "ok" : "failed"}`);
}
⌨️ Terminal
node retry.js
🖥️ Output
Attempt 1 on /api/orders: failed
Attempt 2 on /api/orders: ok
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Declare a constant COURSE with the value "JavaScript" and a variable lesson starting at 1. Increase lesson to 6 and print JavaScript lesson 6.
var a = 1;
{
var a = 2;
}
let b = 1;
{
let b = 2;
}
console.log(a, b);
Show answer
📄 practice2.js
var a = 1;
{
var a = 2;
}
let b = 1;
{
let b = 2;
}
console.log(a, b);
🖥️ Output
2 1
var ignores the block, so the inner var a = 2 replaces the outer value. The inner let b is a new variable that exists only inside its block.
Q3. Swap the values of first = "login" and second = "logout" using a temporary variable.
Show answer
📄 practice3.js
let first = "login";
let second = "logout";
let temp = first;
first = second;
second = temp;
console.log(first, second);
🖥️ Output
logout login
Later in the course you will see the shorter destructuring version: [first, second] = [second, first];.
Q4. This code throws an error. Explain why and fix it while still adding "api" to the tags.
const tags = ["ui"];
tags = [...tags, "api"];
Show answer
Assigning a new array to a const name throws TypeError: Assignment to constant variable. Either change the array in place, or use let if you really need a new array.
Q5. Rewrite this loop so it prints 0, 1 and 2 instead of 3, 3 and 3.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
Show answer
📄 practice5.js
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
🖥️ Output
0
1
2
let creates a new binding for every iteration, so each callback keeps its own value.
Q6. Write a test-run summary: use constants for the suite name and total tests (20), and let counters for passed and failed. Record 17 passes and 3 failures with loops or assignments, then print Checkout suite: 17 passed, 3 failed of 20.
Show answer
📄 practice6.js
const SUITE = "Checkout";
const TOTAL = 20;
let passed = 0;
let failed = 0;
for (let i = 1; i <= TOTAL; i++) {
if (i <= 17) passed++;
else failed++;
}
console.log(`${SUITE} suite: ${passed} passed, ${failed} failed of ${TOTAL}`);
🖥️ Output
Checkout suite: 17 passed, 3 failed of 20
🧠 MCQ Quiz: Variables: var, let, const
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
Which keyword should you use by default for a new variable?
Answer:const. Use const unless the variable needs to be reassigned, then use let.
What happens with const x = 1; x = 2;?
Answer:TypeError: Assignment to constant variable.. Reassigning a const binding throws a TypeError when that line runs.
Is this allowed?
const list = [1];
list.push(2);
Answer: Yes, the array contents can change. const protects the binding, not the contents of the array.
What is the scope of a var declared inside an if block in a function?
Answer: The whole function. var is function-scoped and ignores blocks.
What does this print?
console.log(x);
var x = 5;
Answer:undefined. var declarations are hoisted and initialised with undefined.
What does this throw?
console.log(y);
let y = 5;
Answer:ReferenceError: Cannot access 'y' before initialization. y is in the temporal dead zone until its declaration runs.
What does let a = 1; let a = 2; in the same scope cause?
Answer:SyntaxError: Identifier 'a' has already been declared. Redeclaring with let or const is a syntax error found before the file runs.
Why does a for (var i...) loop with setTimeout print 3, 3, 3?
Answer: There is a single i shared by all callbacks, and it is 3 when they run. let creates a new i per iteration and fixes it.
Which declaration is invalid?
Answer:const LIMIT;. const must be initialised: SyntaxError: Missing initializer in const declaration.
What is globalThis?
Answer: The standard name for the global object in every environment. It is window in browsers and global in Node.js.
💼 Interview Questions and Answers
Q1. What is the difference between var, let and const?
var is function-scoped, can be redeclared, and is hoisted with the value undefined. let and const are block-scoped, cannot be redeclared in the same scope, and are in the temporal dead zone until declared. const must be initialised and cannot be reassigned, though objects it points to can still change. In modern code use const by default, let when reassignment is needed, and avoid var.
Q2. What is the temporal dead zone?
It is the time between entering a scope and running the let, const or class declaration in it. The binding already exists (it is hoisted), but accessing it throws ReferenceError: Cannot access 'x' before initialization. The TDZ exists to catch code that uses a variable before it has a meaningful value.
Q3. Are let and const hoisted?
Yes. All declarations are hoisted to the top of their scope. The difference is initialisation: var is initialised to undefined immediately, while let and const remain uninitialised (TDZ) until their line runs. That is why reading them early throws an error instead of returning undefined.
Q4. Can you change an object declared with const? How do you prevent it?
Yes, its properties can be added, changed or deleted, because const only fixes which object the name refers to. To prevent changes, use Object.freeze(obj), which makes the object’s own properties read-only (shallow). For nested objects you need a deep-freeze helper.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i));
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j));
}
⌨️ Terminal
node interview-loop.js
🖥️ Output
3
3
3
0
1
2
The callbacks run after both loops finish. The var loop shares one i, which ends at 3, so it prints 3 three times. The let loop creates a fresh j per iteration, so it prints 0, 1, 2.
Q6. Why are shared global variables a problem in test automation?
Tests should be independent. If tests read and change a global (for example a shared let currentUser), the result depends on which test ran first, and parallel workers can overwrite each other’s values. This creates flaky tests. Keep data inside each test, create it in hooks or fixtures, and use const for configuration that never changes.
❓ Frequently Asked Questions
🤔 Should I ever use var in 2026?
Not in new code. let and const fix var’s scope and hoisting problems. Learn var so you can read older code and answer interview questions.
🤔 Is const faster than let?
Not in any way you will notice. Choose const because it communicates that the value will not be reassigned and prevents accidental reassignment.
🤔 Can a variable change its type in JavaScript?
Yes. JavaScript is dynamically typed, so let x = 5; x = "five"; is valid. TypeScript can prevent this if you want type safety.
🤔 What is the default value of a declared variable?
A variable declared with let or var but not assigned holds undefined. A const must always be given a value.
🏁 Summary
Variables are named references to values; declare them with const, let or var.
const cannot be reassigned (but object contents can change); let can.
let/const are block-scoped; var is function-scoped and can be redeclared.
All declarations are hoisted, but let/const stay in the temporal dead zone until declared.
Rule of thumb: const by default, let when you must reassign, never var in new code.