JavaScript Loop Programs with Solutions

Print numbers from 1 to 10 (Basic for)

for (let i = 1; i <= 10; i++) {
console.log(i);
}

2️⃣ Print numbers from 10 to 1 (Reverse loop)

for (let i = 10; i >= 1; i--) {
console.log(i);
}

3️⃣ Print even numbers (Loop with if)

for (let i = 1; i <= 20; i++) {
if (i % 2 === 0) {
console.log(i);
}
}

4️⃣ Print odd numbers (Loop with if)

for (let i = 1; i <= 20; i++) {
if (i % 2 !== 0) {
console.log(i);
}
}

5️⃣ Sum of numbers from 1 to 10

let sum = 0;for (let i = 1; i <= 10; i++) {
sum += i;
}console.log(sum);

6️⃣ Multiplication table of 5

for (let i = 1; i <= 10; i++) {
console.log(`5 x ${i} = ${5 * i}`);
}

7️⃣ Nested loop: Print square pattern

for (let i = 1; i <= 3; i++) {
let row = "";
for (let j = 1; j <= 3; j++) {
row += "* ";
}
console.log(row);
}

8️⃣ Nested loop: Number pattern

for (let i = 1; i <= 3; i++) {
let row = "";
for (let j = 1; j <= i; j++) {
row += j + " ";
}
console.log(row);
}

9️⃣ while loop: Print 1 to 5

let i = 1;while (i <= 5) {
console.log(i);
i++;
}

🔟 while loop: Sum of first 5 numbers

let i = 1;
let sum = 0;while (i <= 5) {
sum += i;
i++;
}console.log(sum);

1️⃣1️⃣ do...while: Print 1 to 5

let i = 1;do {
console.log(i);
i++;
} while (i <= 5);

1️⃣2️⃣ do...while: Run at least once

let i = 10;do {
console.log(i);
} while (i < 5);

1️⃣3️⃣ forEach: Print array elements

let arr = [10, 20, 30];arr.forEach(num => console.log(num));

1️⃣4️⃣ forEach: Sum of array

let arr = [1, 2, 3, 4];
let sum = 0;arr.forEach(num => {
sum += num;
});console.log(sum);

1️⃣5️⃣ Loop through string (characters)

let str = "Hello";for (let char of str) {
console.log(char);
}

1️⃣6️⃣ Count vowels in a string

let str = "javascript";
let count = 0;for (let char of str) {
if ("aeiou".includes(char)) {
count++;
}
}console.log(count);

1️⃣7️⃣ Loop through array using for

let arr = [5, 10, 15];for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}

1️⃣8️⃣ Find largest number in array

let arr = [10, 5, 20, 8];
let max = arr[0];for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}console.log(max);

1️⃣9️⃣ Loop through object properties (for...in)

let person = {
name: "John",
age: 25,
city: "Delhi"
};for (let key in person) {
console.log(key + ": " + person[key]);
}

2️⃣0️⃣ Count properties in an object

let obj = {
a: 1,
b: 2,
c: 3
};let count = 0;for (let key in obj) {
count++;
}console.log(count);

Beginner Level

  1. Write a JavaScript program to print numbers from 1 to 10 using a for loop.
  2. Write a JavaScript program to print numbers from 10 to 1 in reverse order.
  3. Write a JavaScript program to print all even numbers between 1 and 100.
  4. Write a JavaScript program to print all odd numbers between 1 and 100.
  5. Write a JavaScript program to calculate the sum of numbers from 1 to N.
  6. Write a JavaScript program to calculate the product of numbers from 1 to N.
  7. Write a JavaScript program to print the multiplication table of a given number.
  8. Write a JavaScript program to print the multiplication tables from 1 to 10.
  9. Write a JavaScript program to count the total number of digits in a given number.
  10. Write a JavaScript program to reverse a given number.

Intermediate Level

  1. Write a JavaScript program to check whether a given number is a palindrome.
  2. Write a JavaScript program to find the sum of digits of a given number.
  3. Write a JavaScript program to find the largest digit in a number.
  4. Write a JavaScript program to find the smallest digit in a number.
  5. Write a JavaScript program to calculate the factorial of a number.
  6. Write a JavaScript program to check whether a number is a prime number.
  7. Write a JavaScript program to print all prime numbers between 1 and N.
  8. Write a JavaScript program to count the total number of prime numbers between 1 and N.
  9. Write a JavaScript program to find the sum of all prime numbers between 1 and N.
  10. Write a JavaScript program to print the Fibonacci series up to N terms.

Pattern Programs

  1. Write a JavaScript program to print a right-angled triangle using *.
  2. Write a JavaScript program to print an inverted right-angled triangle.
  3. Write a JavaScript program to print a pyramid pattern using *.
  4. Write a JavaScript program to print an inverted pyramid pattern.
  5. Write a JavaScript program to print a diamond pattern.
  6. Write a JavaScript program to print Floyd’s Triangle.
  7. Write a JavaScript program to print Pascal’s Triangle.
  8. Write a JavaScript program to print a square pattern using *.
  9. Write a JavaScript program to print a hollow square pattern.
  10. Write a JavaScript program to print a hollow pyramid pattern.

Advanced Loop Programs

  1. Write a JavaScript program to find all Armstrong numbers between 1 and N.
  2. Write a JavaScript program to check whether a given number is an Armstrong number.
  3. Write a JavaScript program to find the Greatest Common Divisor (GCD) of two numbers.
  4. Write a JavaScript program to find the Least Common Multiple (LCM) of two numbers.
  5. Write a JavaScript program to convert a decimal number to binary.
  6. Write a JavaScript program to convert a binary number to decimal.
  7. Write a JavaScript program to calculate the power of a number without using built-in methods.
  8. Write a JavaScript program to print all perfect numbers between 1 and N.
  9. Write a JavaScript program to check whether a given number is a perfect number.
  10. Write a JavaScript program to find the sum of all even numbers between 1 and N.

Nested Loop Programs

  1. Write a JavaScript program to print a multiplication table using nested loops.
  2. Write a JavaScript program to print a number triangle pattern.
  3. Write a JavaScript program to print a character triangle pattern.
  4. Write a JavaScript program to print a checkerboard (# and *) pattern.
  5. Write a JavaScript program to print a hollow rectangle using nested loops.
  6. Write a JavaScript program to print an X pattern using *.
  7. Write a JavaScript program to print a butterfly pattern.
  8. Write a JavaScript program to print a sandglass pattern.
  9. Write a JavaScript program to print a zigzag pattern.
  10. Write a JavaScript program to create a simple number guessing game using loops.

JavaScript Loops: for, while, do…while, for…of and for…in with Examples

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.

LoopBest for
forCounting: a known number of iterations, or when you need the index
whileRepeating until a condition changes (unknown number of iterations)
do...whileLike while, but the body must run at least once
for...ofValues of arrays, strings, Maps, Sets
for...inKeys (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
}
  1. Initialisation runs once before the loop, usually let i = 0.
  2. Condition is checked before every iteration; the loop stops when it is falsy.
  3. 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");

⌨️ Terminal

node while.js

🖥️ Output

Attempt 1: failed
Attempt 2: failed
Attempt 3: connected
Ready

⚠️ 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);
}

⌨️ Terminal

node for-in.js

🖥️ Output

browser = chromium
headless = true
retries = 2
browser   -> chromium
headless  -> true
retries   -> 2

⚠️ 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...offor...in
Gives youValuesKeys (as strings)
Works onIterables: arrays, strings, Map, SetObjects (any object)
Use for arrays?YesNo
Plain objectsNo (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:

📄 data-driven.js

function isValidEmail(email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

const cases = [
  { input: "qa@sqatools.in", expected: true },
  { input: "first.last@company.co.uk", expected: true },
  { input: "missing-at.com", expected: false },
  { input: "spaces in@mail.com", expected: false },
  { input: "", expected: false },
];

let failures = 0;
for (const { input, expected } of cases) {
  const actual = isValidEmail(input);
  const ok = actual === expected;
  if (!ok) failures++;
  console.log(`${ok ? "PASS" : "FAIL"}  ${JSON.stringify(input).padEnd(28)} expected ${expected}, got ${actual}`);
}
console.log(`${cases.length - failures}/${cases.length} passed`);

⌨️ Terminal

node data-driven.js

🖥️ Output

PASS  "qa@sqatools.in"             expected true, got true
PASS  "first.last@company.co.uk"   expected true, got true
PASS  "missing-at.com"             expected false, got false
PASS  "spaces in@mail.com"         expected false, got false
PASS  ""                           expected false, got false
5/5 passed

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]}`);
}

🖥️ Output

{ pass: 3, fail: 1, skip: 1 }
pass: 3
fail: 1
skip: 1

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.

  1. How many times does for (let i = 0; i < 5; i++) run its body?
  2. Which loop always runs its body at least once?
  3. What does for (const x of ["a", "b"]) give you in x?
  4. What does for (const k in { a: 1, b: 2 }) give you in k?
  5. Why should you avoid for…in on arrays?
  6. What happens with for (const x of { a: 1 })?
  7. With arr = ["x", "y"], what is printed last by for (let i = 0; i <= arr.length; i++) console.log(arr[i])?
  8. Which loop does not wait for await inside its callback?
  9. How many times does the inner body run?
    for (let i = 0; i < 3; i++)
      for (let j = 0; j < 4; j++)
        count++;
  10. How do you get both key and value when looping over an object with for…of?

💼 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.

Next, continue with Lesson 16: break, continue and Labels. For extra practice, solve the JavaScript loop practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

GitHub Fundamentals

1. What is GitHub?

  • GitHub is a platform to store, manage, and collaborate on code.
  • It uses Git (a version control system).

👉 Think of GitHub as:

“Google Drive for code + collaboration tools for developers”


2. What is Git?

  • Git tracks changes in your code.
  • Helps you:
    • Save versions
    • Undo mistakes
    • Work with teams

3. Repository (Repo)

A repository is a project folder stored on GitHub.

Example:

my-project/
├── index.html
├── style.css
└── script.js

👉 This entire folder = 1 repository


4. Clone a Repository

Copy a GitHub repo to your local machine.

Command:

git clone https://github.com/user/project.git

Example:

git clone https://github.com/deepesh/my-app.git

5. Basic Git Workflow

The most important concept 👇

Working Directory → Staging Area → Repository

Steps:

git add file.js      # Add file to staging
git commit -m "Added feature" # Save changes
git push # Upload to GitHub

6. Commit

A commit is a snapshot of your code.

Example:

git commit -m "Fixed login bug"

👉 Good commit message = clear + meaningful


7. Branch

A branch lets you work on features without affecting main code.

Example:

git branch feature-login
git checkout feature-login

Or shortcut:

git checkout -b feature-login

8. Merge

Combine changes from one branch into another.

Example:

git checkout main
git merge feature-login

9. Pull Request (PR)

  • A Pull Request is used to merge code on GitHub.
  • You request others to review your code.

👉 Workflow:

  1. Create branch
  2. Push code
  3. Open PR
  4. Review → Merge

10. Push & Pull

Push (upload changes):

git push origin main

Pull (get latest changes):

git pull origin main

11. Fork

A fork is a copy of someone else’s repository.

👉 Used in open-source contributions.


12. .gitignore

Tells Git which files to ignore.

Example:

node_modules/
.env
*.log

13. Real Example Workflow

Let’s say you’re building a JavaScript project:

Step 1: Initialize repo

git init

Step 2: Add files

git add .

Step 3: Commit

git commit -m "Initial project setup"

Step 4: Connect GitHub

git remote add origin https://github.com/user/project.git

Step 5: Push

git push -u origin main

14. Common Commands Cheat Sheet

CommandPurpose
git initStart repo
git cloneCopy repo
git addStage changes
git commitSave changes
git pushUpload
git pullDownload updates
git branchList branches
git checkoutSwitch branch

15. Best Practices

  • ✅ Commit often
  • ✅ Use clear commit messages
  • ✅ Use branches for features
  • ✅ Pull before push
  • ❌ Don’t push sensitive data

🎯 Mini Practice Exercise

Try this:

  1. Create a folder
  2. Add a file app.js
  3. Run:
  4. Push it to GitHub
git init
git add .
git commit -m "First commit"
git push

Pro Tip

Start with:

  • Personal projects
  • Practice branching + PRs

That’s how real developers learn GitHub fast.

16. GitHub Issues (Task Tracking)

  • Issues are used to track bugs, tasks, or feature requests.

Example:

You create an issue:

Title: Fix login error
Description: Login fails when password is incorrect

👉 You can:

  • Assign team members
  • Add labels (bug, feature, urgent)
  • Track progress

📌 17. Labels (Organizing Work)

Labels help categorize issues.

Example labels:

  • bug 🐛
  • enhancement 🚀
  • documentation 📄

👉 Helps teams quickly understand task types.


📊 18. GitHub Projects (Kanban Board)

GitHub provides project boards similar to Trello.

Example workflow:

To Do → In Progress → Done

👉 You can drag issues between columns.


🔐 19. README.md File

This is the first file people see in your repo.

Example:

# My AppThis is a simple JavaScript project.## Features
- Login system
- Dashboard

👉 A good README increases project visibility.


⚙️ 20. GitHub Actions (Automation)

  • GitHub Actions lets you automate workflows.

Example:

Run tests automatically when code is pushed.

name: Test App
on: [push]jobs:
test:
runs-on: ubuntu-latest
steps:
- run: echo "Running tests..."

👉 Used for:

  • CI/CD (Continuous Integration / Deployment)
  • Auto testing
  • Deployment

🔁 21. Pull vs Fetch

Git Pull:

git pull origin main

👉 Fetch + merge

Git Fetch:

git fetch

👉 Only downloads changes (no merge)


🔄 22. Merge Conflict (Important!)

Occurs when Git can’t merge automatically.

Example conflict:

<<<<<<< HEAD
console.log("Hello");
=======
console.log("Hi");
>>>>>>> branch

👉 You must manually fix it:

console.log("Hello Hi");

Then:

git add .
git commit -m "Resolved conflict"

🧪 23. Stash (Temporary Save)

Save changes without committing.

git stash

Restore:

git stash pop

👉 Useful when switching branches quickly.


📜 24. Git Log (History)

View commit history:

git log

Short version:

git log --oneline

⏪ 25. Undo Changes

Undo staged file:

git reset file.js

Undo last commit:

git reset --soft HEAD~1

Discard changes:

git checkout -- file.js

🌐 26. Remote Repository

Link your local repo to GitHub.

git remote add origin https://github.com/user/repo.git

Check:

git remote -v

🔒 27. SSH vs HTTPS

Two ways to connect GitHub:

HTTPS:

https://github.com/user/repo.git

SSH:

git@github.com:user/repo.git

👉 SSH is more secure (no need to enter password repeatedly)


📦 28. Fork + Clone + PR (Real Open Source Flow)

Step-by-step:

  1. Fork repository on GitHub
  2. Clone it:
git clone https://github.com/your-username/repo.git
  1. Create branch:
git checkout -b fix-bug
  1. Make changes + commit
  2. Push:
git push origin fix-bug
  1. Create Pull Request

👉 This is how open-source contributions work.


🧱 29. Rebase (Advanced Concept)

Instead of merge, you can use rebase for cleaner history.

git checkout feature
git rebase main

👉 Keeps history linear (no extra merge commits)


🏷️ 30. Tags (Versioning)

Used for releases.

git tag v1.0
git push origin v1.0

👉 Example:

  • v1.0 → first release
  • v2.0 → major update

Real-World Scenario (Important)

Scenario: Team Development

  1. Developer A creates feature branch
  2. Developer B works on another branch
  3. Both create Pull Requests
  4. Code review happens
  5. Merge into main

👉 This prevents breaking the main codebase.


🧠 Pro Learning Tips

  • Practice daily with small repos
  • Break code → fix using Git
  • Try merge conflicts intentionally
  • Explore open-source repos

💻 Practice Tasks (Next Level)

Try these:

  1. Create 2 branches and merge them
  2. Create a merge conflict and resolve it
  3. Use git stash while switching branches
  4. Create a Pull Request on your own repo
  5. Add a README with project details

JavaScript If-Condition Programs

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");
}

🔹 10. Character type (if-else if)

let ch = 'A';if (ch >= 'A' && ch <= 'Z') {
console.log("Uppercase");
} else if (ch >= 'a' && ch <= 'z') {
console.log("Lowercase");
} else {
console.log("Other");
}

🔹 11. Nested if (positive & even)

let num = 8;if (num > 0) {
if (num % 2 === 0) {
console.log("Positive and Even");
}
}

🔹 12. Nested if (login system)

let username = "admin";
let password = "1234";if (username === "admin") {
if (password === "1234") {
console.log("Login successful");
} else {
console.log("Wrong password");
}
} else {
console.log("User not found");
}

🔹 13. Nested if (marks & distinction)

let marks = 75;if (marks >= 40) {
if (marks >= 75) {
console.log("Distinction");
} else {
console.log("Pass");
}
} else {
console.log("Fail");
}

🔹 14. One-line if (ternary)

let num = 10;console.log(num > 0 ? "Positive" : "Not positive");

🔹 15. One-line even/odd

let num = 7;console.log(num % 2 === 0 ? "Even" : "Odd");

🔹 16. One-line pass/fail

let marks = 35;console.log(marks >= 40 ? "Pass" : "Fail");

🔹 17. Multiple conditions (if)

let num = 15;if (num % 3 === 0 && num % 5 === 0) {
console.log("Divisible by 3 and 5");
}

🔹 18. Temperature check (if-else if)

let temp = 30;if (temp > 40) {
console.log("Hot");
} else if (temp > 20) {
console.log("Warm");
} else {
console.log("Cold");
}

🔹 19. Triangle validity (if)

let a = 3, b = 4, c = 5;if (a + b > c && a + c > b && b + c > a) {
console.log("Valid triangle");
}

🔹 20. Simple calculator (if-else if)

let a = 10, b = 5;
let op = "+";if (op === "+") {
console.log(a + b);
} else if (op === "-") {
console.log(a - b);
} else if (op === "*") {
console.log(a * b);
} else if (op === "/") {
console.log(a / b);
} else {
console.log("Invalid operator");
}

JavaScript if Condition Practice Programs (Without Solution)

Beginner Level

  1. Check whether a number is positive.
  2. Check whether a number is negative.
  3. Check whether a number is zero.
  4. Check whether a number is even or odd.
  5. Check whether a person is eligible to vote.
  6. Check whether a student passed or failed.
  7. Find the greater number between two numbers.
  8. Find the smaller number between two numbers.
  9. Check whether a character is a vowel or consonant.
  10. Check whether a year is a leap year.

Intermediate Level

  1. Check whether a number is divisible by 5.
  2. Check whether a number is divisible by both 3 and 7.
  3. Find the largest among three numbers.
  4. Find the smallest among three numbers.
  5. Check whether a character is uppercase or lowercase.
  6. Check whether a number is a 3-digit number.
  7. Check whether a person is a child, teenager, or adult.
  8. Check whether a triangle is valid based on angles.
  9. Check whether a temperature is hot, cold, or moderate.
  10. Calculate bonus based on salary conditions.

Advanced Beginner Level

  1. Check whether a number is divisible by 2 but not by 5.
  2. Check whether a student got distinction, first class, second class, or failed.
  3. Check whether a number is within a given range.
  4. Check whether three sides can form a triangle.
  5. Find the middle number among three numbers.
  6. Check whether a character is an alphabet, digit, or special character.
  7. Check whether a user entered the correct username and password.
  8. Check whether a number is a multiple of 10.
  9. Check whether a person is eligible for a driving license.
  10. Check whether an entered day is weekday or weekend.

JavaScript if, else if and else Statements: Conditions with Examples

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));

⌨️ Terminal

node wrong-order.js

🖥️ Output

C

🔗 Combining Conditions with &&, || and !

📄 combined.js

function canCheckout(user, cart) {
  if (user.isLoggedIn && cart.items > 0 && !cart.hasErrors) {
    return "Checkout allowed";
  } else if (!user.isLoggedIn) {
    return "Please log in";
  } else if (cart.items === 0) {
    return "Cart is empty";
  } else {
    return "Fix cart errors first";
  }
}

console.log(canCheckout({ isLoggedIn: true }, { items: 2, hasErrors: false }));
console.log(canCheckout({ isLoggedIn: false }, { items: 2, hasErrors: false }));
console.log(canCheckout({ isLoggedIn: true }, { items: 0, hasErrors: false }));
console.log(canCheckout({ isLoggedIn: true }, { items: 1, hasErrors: true }));

⌨️ Terminal

node combined.js

🖥️ Output

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:

📄 lookup.js

const statusText = {
  200: "OK",
  201: "Created",
  400: "Bad Request",
  401: "Unauthorized",
  404: "Not Found",
  500: "Server Error",
};

for (const code of [200, 404, 418]) {
  console.log(code, statusText[code] ?? "Unknown status");
}

⌨️ Terminal

node lookup.js

🖥️ Output

200 OK
404 Not Found
418 Unknown status

⚠️ Common Mistakes

Using = instead of ===

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:

📄 classify.js

function classify(result) {
  if (result.skipped) return "⏭️  SKIPPED";
  if (result.error) return `❌ ERROR (${result.error})`;

  const { passed, total, durationMs } = result;
  if (passed === total && durationMs > 60_000) {
    return "⚠️  PASSED BUT SLOW";
  } else if (passed === total) {
    return "✅ PASSED";
  } else if (passed >= total * 0.9) {
    return `🟡 MOSTLY PASSED (${total - passed} failed)`;
  } else {
    return `❌ FAILED (${total - passed} failed)`;
  }
}

const runs = [
  { name: "smoke", passed: 12, total: 12, durationMs: 41_000 },
  { name: "regression", passed: 188, total: 200, durationMs: 540_000 },
  { name: "checkout", passed: 20, total: 20, durationMs: 95_000 },
  { name: "payments", passed: 3, total: 10, durationMs: 30_000 },
  { name: "legacy", skipped: true },
  { name: "api", error: "ECONNREFUSED" },
];

for (const run of runs) {
  console.log(run.name.padEnd(11), classify(run));
}

⌨️ Terminal

node classify.js

🖥️ Output

smoke       ✅ PASSED
regression  🟡 MOSTLY PASSED (12 failed)
checkout    ⚠️  PASSED BUT SLOW
payments    ❌ FAILED (7 failed)
legacy      ⏭️  SKIPPED
api         ❌ ERROR (ECONNREFUSED)
  • Guard clauses handle “skipped” and “error” first, so the rest only deals with real results.
  • The slow-but-passing check comes before the plain “passed” check, because the more specific condition must win.
  • const { passed, total, durationMs } = result; is destructuring, a shortcut covered in Module 6.

📝 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. Write checkAge(age) that prints Minor under 18, Adult from 18 to 59 and Senior from 60. Test it with 15, 18, 59 and 60.

Show answer

📄 practice1.js

function checkAge(age) {
  if (age < 18) {
    console.log(age, "Minor");
  } else if (age < 60) {
    console.log(age, "Adult");
  } else {
    console.log(age, "Senior");
  }
}

[15, 18, 59, 60].forEach(checkAge);

🖥️ Output

15 Minor
18 Adult
59 Adult
60 Senior

Test the boundary values (18, 59, 60) as well as typical values; boundaries are where off-by-one bugs hide.

Q2. Print whether a year is a leap year: divisible by 4, except years divisible by 100, unless also divisible by 400. Test 2024, 1900, 2000 and 2026.

Show answer

📄 practice2.js

function isLeap(year) {
  if (year % 400 === 0) return true;
  if (year % 100 === 0) return false;
  return year % 4 === 0;
}

for (const y of [2024, 1900, 2000, 2026]) {
  console.log(y, isLeap(y) ? "leap" : "not leap");
}

🖥️ Output

2024 leap
1900 not leap
2000 leap
2026 not leap

Q3. Rewrite this nested code with guard clauses.

function login(user) {
  if (user) {
    if (user.active) {
      return "Welcome " + user.name;
    } else {
      return "Account disabled";
    }
  } else {
    return "Unknown user";
  }
}
Show answer

📄 practice3.js

function login(user) {
  if (!user) return "Unknown user";
  if (!user.active) return "Account disabled";
  return `Welcome ${user.name}`;
}

console.log(login(null));
console.log(login({ name: "Asha", active: false }));
console.log(login({ name: "Asha", active: true }));

🖥️ Output

Unknown user
Account disabled
Welcome Asha

Q4. Validate a password: at least 8 characters, contains a digit, and is not equal to "password1". Print the first rule that fails, or Valid.

Show answer

📄 practice4.js

function validate(pw) {
  if (pw.length < 8) return "Too short";
  if (!/\d/.test(pw)) return "Needs a digit";
  if (pw.toLowerCase() === "password1") return "Too common";
  return "Valid";
}

for (const pw of ["abc1", "abcdefgh", "Password1", "qaTester7"]) {
  console.log(pw.padEnd(10), validate(pw));
}

🖥️ Output

abc1       Too short
abcdefgh   Needs a digit
Password1  Too common
qaTester7  Valid

Q5. Replace this else if chain with a lookup object and a default value.

if (browser === "chromium") engine = "Blink";
else if (browser === "firefox") engine = "Gecko";
else if (browser === "webkit") engine = "WebKit";
else engine = "unknown";
Show answer

📄 practice5.js

const ENGINES = { chromium: "Blink", firefox: "Gecko", webkit: "WebKit" };

for (const browser of ["firefox", "webkit", "opera"]) {
  const engine = ENGINES[browser] ?? "unknown";
  console.log(browser, "->", engine);
}

🖥️ Output

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.

  1. When does the block of if (value) { ... } run?
  2. In an if / else if / else chain, how many blocks run?
  3. What is printed?
    const n = 95;
    if (n >= 60) console.log("C");
    else if (n >= 90) console.log("A");
  4. What does if (x = 5) do?
  5. What is 3 < 2 < 1?
  6. What is a guard clause?
  7. Which is the clearest way to check whether role is “admin”, “owner” or “editor”?
  8. Why should you always use braces with if?
  9. What runs here?
    if (false); {
      console.log("hi");
    }
  10. When is a lookup object better than an else if chain?

💼 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.

Next, continue with Lesson 14: switch Statement. For extra practice, solve the JavaScript if-else practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Github Guide

Steps to Create a GitHub Account

  1. Go to https://github.com/
  2. Click on the signup button.
  3. Enter email ID
  4. Enter password
  5. Provide a unique Username,
  6. click on the checkbox -> click on the create account button.
  7. It will show some puzzles to verify -> we have to solve.
  8. User will receive a verification code via email -> provide the code on the GitHub screen.
  9. Account creation is Successful.

Steps to Create a GitHub Repository

  1. Go to the GitHub account
  2. Click on the create repository button.
  3. Provide repository name: AutomationPractice
  4. Provide a description. e.g. Automation practice for the user.
  5. Select the Repo visibility option Public/Private.
  6. Select the readme file option.
  7. Click on the Create repository button.
  8. Repository created successfully.

Steps to install the GitHub client

  1. Download the Git client from the given link
    https://github.com/git-for-windows/git/releases/download/v2.53.0.windows.2/Git-2.53.0.2-64-bit.exe
  2. Double-click on the exe file and initiate installation with exe
    , select all default options, and complete the installation.
  3. Create a folder in C Drive with the name GithubCode, folder path should be C:\GithubCode
  4. Open folder and right-click -> show more options -> click on open git bash here.
  5. It will open the Git terminal in the C:\GithubCode folder.
  6. Run a command to check the git option
    git –help
  7. It will show available git commands

Steps to Add User Credentials in Git Config File

  1. Open the Git terminal in the C:\GitHubCode folder
  2. Run the command below to open the config file
    -> git config –global –edit
    -> It will open the config file in the vi editor
  3. Press i to enable insert mode, it should show –insert– in the bottom.
  4. 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
  5. Make sure to remove # from the name and email line in the config file.
  6. Press the ESCAPE key to disabled insert mode.
  7. start type :wq and press enter
    -> It will save the configuration details.

Steps to Clone the Repository on the User’s Machine

  1. Go to the GitHub server, log in with your credentials
  2. Navigate to the repository that we have already created.
  3. Click on the Code (green color) button, and copy the repository from there.
  4. Open the Git terminal in the C:\GitHubCode folder.
  5. Run the command below to clone the repo
    -> git clone https://github.com/Divya4255/AutomationPractice.git
  6. Hit Enter -> It will clone repository from server to your local machine.
  7. The repository folder will be created on the local machine.

Steps to Create a New File and Push to the GitHub Server

  1. Create a text file in the git repository folder (AutomationPractice) and rename as demo_file.txt
  2. Open the text file and add some content to the file -> save the file.
  3. Open the Git terminal in C:\GitHubCode\AutomationPractice folder.
  4. Run the git status command
    -> git status: it will show the new demo file in red color.
  5. Run the git add command
    -> git add file_path/filename # It will add the file to GitHub tracking
  6. Check the status again.
    -> git status # It will show the demo file in green color.
  7. Initiate commit operation
    -> git commit -m “adding new file to repo.”
    -> It will complete the commit operation.
  8. 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:

  1. Create three different file and push them to the server.
  2. Update file1 and push(git status, git add, git commit, git push) it.
  3. Rename file2 and push it from the terminal.
  4. Delete file3 and push it from terminal.

Create a Common Repo and Provide Access

  1. Create a repository with the name: e.g., GTM_PlaywrightTS_BATCH11
  2. Get students’ email and provide Access to collaborate.
    Go to Repository -> Settings -> Collaborators -> Add People -> Enter Your email -> Select User -> Add to Repository
  3. People will receive an invitation via email.
  4. Open the email, click View Invitation, then accept the invitation.
  5. Everyone has to accept the invitation.
  6. 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.
  7. Once the invitation is accepted, the user will be able to see the common repository.

Clone the Common Repo, Add folder your name

  1. Go to the common repository -> click on code (green button)
    -> click on copy clipboard to copy URL.
  2. Open the Git terminal in the C:\GitHubCode folder on the local system
  3. Run this command to clone the common repository
    -> git clone https://github.com/sqatools/GTM_PlaywrightTS_BATCH11.git
  4. It will clone the command repository into a C:\GitHubCode to the local directory.
    -> repository folder name: GTM_PlaywrightTS_BATCH11
  5. Create folder with your name in repo e.g. Deepesh and Add file inside the your folder e.g. first_file.txt
  6. Navigate back to git terminal.
  7. ON git terminal run below command to go inside repository folder.
    cd GTM_PlaywrightTS_BATCH11 -> It will open GTM_PlaywrightTS_BATCH11 folder.
  8. Check status using below command
    -> git status : New Folder name will show in red color.
  9. Run git add command
    -> git add /FolderName
  10. Initiate commit operation.
    -> git commit -m “added”
  11. Perform git push operation
    -> git push
  12. 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
  1. Go to Git Repository on server : GTM_PlaywrightTS_BATCH11
  2. Click on repository dropdown. default is main
  3. click on view all branches.
  4. 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.
  5. Open git terminal in repository folder
  6. run command to update the repo
    -> git pull (all newly created branches will show in the console output)
  7. Check current active branch
    -> git branch : It will show main as active branch in green color.
  8. Switch to new branch.
    -> git checkout deepesh_branch
  9. check again active branch
    -> git branch : your branch will show as active branch in green color e.g. deepesh_branch
  10. 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

  1. Run git add command
    -> git add
  2. Initiate commit operation
    -> git commit -m “added new file to feature branch”
  3. Initiate push operation
    -> git push : file will push to the server on dedicated branch.
  4. Go to GitHub server and verify file is available in dedicated folder in your branch.
################### Create pull from server
  1. Go to server and navigate to repository.
  2. Click on “Compare & pull request” button (green button)
  3. Provide pull request description.
  4. Add reviwers to review the code.
  5. Click on create pull button.
################### Create workflow file in branch
  1. Go to repository on GitHub server
  2. Navigate to Actions Tab.
  3. Click on New Workflow (green color) button
  4. Select any workflow from given list. e.g. simple workflow
  5. click on configure button
  6. Select your branch from left side dropdown e.g. deepesh_branch.
  7. 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” ]
  8. click on commit changes button.
  9. It will open pop to provide commit message -> we can click on commit changes
    and push to the current branch.
  10. It will create workflow on your dedicated branch and execute along with each
    PR.
########## Resolve Merge conflict

conflict scenario

  1. Create file1 in main branch add some code from line 1 to 10.
  2. Create new branch from main branch and then modify same file1 and same line numbers from 1 to 10.
  3. In main branch, modify same on same number of lines and push it.
  4. Create pull request from feature to main branch
  5. It will create conflict.
  6. We have to resolve conflict and merge the change
Steps to reproduce conflict scenario
  1. 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
  2. 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”)
    }
  3. 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.
  4. Create a branch from local git bash terminal.
    -> git checkout -b “dy_conflict_branch”
  5. 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”)
    }
  6. 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”
  7. run below command to push local branch to server
    -> git push –set-upstream origin dy_conflict_branch
    -> push will be successful in feature.
  8. 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.
  9. 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”)
    }
  10. push the file change in main branch.
    -> git status
    -> git add
    -> git commit -m “updated file”
    -> git push (repeat pull and push commands)
  11. 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.
  12. 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 ——

  1. Go back to git terminal
  2. switch to feature branch.
    -> git checkout dy_conflict_branch
  3. 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.
  4. 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
}

  1. 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”)
    }
  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
  3. 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.
  4. We can merge changes from feature to main branch.

JavaScript Type Conversion and Coercion: Explicit vs Implicit with Examples

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.


🔤 Convert to String

📄 to-string.js

console.log(String(123));          // "123"
console.log(String(true));         // "true"
console.log(String(null));         // "null"
console.log(String(undefined));    // "undefined"
console.log(String([1, 2, 3]));    // "1,2,3"
console.log(String({ a: 1 }));     // "[object Object]"

const price = 7.5;
console.log(price.toString(), price.toFixed(2)); // toFixed rounds and returns a string
console.log((255).toString(16));   // to hexadecimal
console.log(`${42}`, 42 + "");     // template literal and + "" also convert

⌨️ Terminal

node to-string.js

🖥️ Output

123
true
null
undefined
1,2,3
[object Object]
7.5 7.50
ff
42 42
  • 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.

📄 to-number.js

console.log(Number("42"), Number("3.14"), Number("  12  "));
console.log(Number(""), Number("12px"), Number("abc"));
console.log(Number(true), Number(false), Number(null), Number(undefined));
console.log(Number([]), Number([7]), Number([1, 2]));

console.log(parseInt("12px"), parseFloat("3.75rem"), parseInt("3.99"));
console.log(parseInt("px12"), parseInt("101", 2), parseInt("ff", 16));
console.log(+"8", +"", +"8.5kg");   // unary plus works like Number()

⌨️ Terminal

node to-number.js

🖥️ Output

42 3.14 12
0 NaN NaN
1 0 0 NaN
0 7 NaN
12 3.75 3
NaN 5 255
8 0 NaN
InputNumber()parseInt()parseFloat()
"42"424242
"3.99"3.9933.99
"12px"NaN1212
""0NaNNaN
null0NaNNaN
true1NaNNaN

⚠️ 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.

📄 to-boolean.js

const values = [
  ["0", 0], ["-0", -0], ["0n", 0n], ["\"\"", ""], ["null", null], ["undefined", undefined],
  ["NaN", NaN], ["false", false], ["\"0\"", "0"], ["\"false\"", "false"], ["\" \"", " "],
  ["[]", []], ["{}", {}], ["-1", -1],
];
for (const [label, value] of values) {
  console.log(label.padEnd(10), "->", Boolean(value));
}

⌨️ Terminal

node to-boolean.js

🖥️ Output

0          -> false
-0         -> false
0n         -> false
""         -> false
null       -> false
undefined  -> false
NaN        -> false
false      -> false
"0"        -> true
"false"    -> true
" "        -> true
[]         -> true
{}         -> true
-1         -> true

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.
  • Conditions (if, &&, ||, !): convert to boolean.

📄 coercion.js

console.log("5" + 2);        // string + number -> "52"
console.log(5 + 2 + "1");    // left to right: 7 + "1" -> "71"
console.log("1" + 5 + 2);    // "15" + 2 -> "152"
console.log("5" - 2);        // - always uses numbers -> 3
console.log("6" * "2");      // 12
console.log("10" / "4");     // 2.5
console.log(true + 1);       // true -> 1
console.log(null + 1);       // null -> 0
console.log(undefined + 1);  // undefined -> NaN
console.log([] + []);        // both become "" -> ""
console.log([1, 2] + [3]);   // "1,2" + "3"
console.log("10" > "9");     // both strings: compared alphabetically -> false
console.log("10" > 9);       // one number: numeric comparison -> true

⌨️ Terminal

node coercion.js

🖥️ Output

52
71
152
3
12
2.5
2
1
NaN

1,23
false
true

⚠️ 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 });

⌨️ Terminal

node parse-ui.js

🖥️ Output

Line prices: [ 1299.5, 450, 50 ]
Total: 1799.50
{ shown: 25, all: 1024 }
  • 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);

⌨️ Terminal

node dates-json.js

🖥️ Output

1795429800000
2026-11-23T10:30:00.000Z
1970-01-01T00:00:00.000Z
{"id":7,"tags":["smoke"],"active":true} string
smoke object

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".

Show answer

📄 practice2.js

console.log("3" + 4 + 5);
console.log(3 + 4 + "5");
console.log("3" * "4");
console.log("10" - "4" + "1");

🖥️ Output

345
75
12
61

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);
  }
}

🖥️ Output

3
Invalid quantity: ""
Invalid quantity: "abc"
Invalid quantity: "2.5"

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.

  1. What is "5" + 2?
  2. What is "5" - 2?
  3. What does Number("") return?
  4. What does parseInt("12px", 10) return?
  5. Which check correctly detects NaN?
  6. Which of these is truthy?
  7. What is "10" > "9"?
  8. What does (7.456).toFixed(2) return?
  9. What is null + 1?
  10. Why should you pass 10 as the second argument to parseInt?

💼 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.

Q3. Explain the output of these expressions.

📄 tricky.js

console.log([] + {});
console.log(1 + "2" - 1);
console.log(true + true);
console.log("b" + "a" + +"a" + "a");

⌨️ Terminal

node tricky.js

🖥️ Output

[object Object]
11
2
baNaNa
  • [] + {}: 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?

  1. Get the text (for example await locator.textContent()) and trim it.
  2. Remove formatting such as currency symbols, thousands separators and units with a regular expression.
  3. Convert with Number() and validate with Number.isFinite(); throw a clear error if it fails.
  4. Compare with a tolerance for decimals, or compare integer cents, to avoid floating-point issues.
  5. 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 ===.


🏁 Summary

  • Explicit conversion: String(), Number(), Boolean(), parseInt(s, 10), parseFloat(), toFixed().
  • + joins strings if either side is a string; -, *, / always convert to numbers.
  • Number("") and Number(null) are 0; Number(undefined) and invalid text are NaN.
  • Check numbers with Number.isNaN() or Number.isFinite(), never with === NaN.
  • Text from pages, files and arguments is always a string: clean it and convert it before comparing.

Next, continue with Lesson 9: Numbers, Math and BigInt. For extra practice, solve the JavaScript type conversion practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Data Types: Primitives, Objects and typeof Explained

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.

TypeExampleUsed for
string"Asha", 'QA', `hi`Text
number42, 3.14, -7, NaNIntegers and decimals
bigint9007199254740993nWhole numbers larger than 253
booleantrue, falseYes/no conditions
undefinedundefinedA value that was never set
nullnullAn intentionally empty value
symbolSymbol("id")Unique keys
object{}, [], functions, datesCollections 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.

📄 objects.js

const user = { name: "Asha", role: "tester" };   // plain object
const scores = [91, 78, 85];                     // array (an object with numeric keys)
const greet = function () { return "hi"; };      // function (a callable object)
const today = new Date(2026, 10, 23);            // Date object
const pattern = /qa/i;                           // regular expression

console.log(typeof user, typeof scores, typeof greet);
console.log(typeof today, typeof pattern);
console.log(Array.isArray(scores), Array.isArray(user));
console.log(today instanceof Date);

⌨️ Terminal

node objects.js

🖥️ Output

object object function
object object
true false
true
  • typeof returns "object" for arrays, dates and regular expressions, so it cannot tell them apart.
  • Use Array.isArray(value) to check for an array and value instanceof Date for dates.
  • Functions are objects too, but typeof reports them as "function" because that check is so useful.

🔍 The typeof Operator and Its Quirks

typeof value returns the type as a string. It is safe to use even on names that were never declared.

ExpressionResultNote
typeof "hi""string"
typeof 3.5"number"
typeof NaN"number"NaN is a special number value
typeof 10n"bigint"
typeof undefined"undefined"
typeof null"object"A historical bug, kept for compatibility
typeof []"object"Use Array.isArray()
typeof function(){}"function"
typeof notDeclared"undefined"No ReferenceError

A small helper that returns a more precise type name is common in test utilities:

📄 typename.js

function typeName(value) {
  if (value === null) return "null";
  if (Array.isArray(value)) return "array";
  if (value instanceof Date) return "date";
  return typeof value;
}

const samples = [
  ["\"text\"", "text"], ["7", 7], ["NaN", NaN], ["5n", 5n], ["true", true],
  ["undefined", undefined], ["null", null], ["[1]", [1]], ["{ a: 1 }", { a: 1 }],
  ["new Date()", new Date()], ["() => {}", () => {}],
];
for (const [label, value] of samples) {
  console.log(label.padEnd(12), "->", typeName(value));
}

⌨️ Terminal

node typename.js

🖥️ Output

"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:

undefinednull
MeaningNot set yet / missingDeliberately empty
Who sets itUsually JavaScript itselfUsually you (or an API)
Where you see itUnassigned variables, missing properties, functions with no return, missing argumentsAPI fields with no value, “clear this field”
typeof"undefined""object"
In JSONOmitted from the outputKept 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);

⌨️ Terminal

node null-undefined.js

🖥️ Output

undefined
undefined
undefined
null
{"b":null}
true false

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);

⌨️ Terminal

node clone.js

🖥️ Output

{ name: 'asha', address: { city: 'Delhi' } }
{ name: 'asha', address: { city: 'Mumbai' } }

⚠️ 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`);

⌨️ Terminal

node schema-check.js

🖥️ Output

PASS id: expected number, got number
PASS email: expected string, got string
PASS active: expected boolean, got boolean
PASS roles: expected array, got array
PASS manager: expected null, got null
PASS createdAt: expected string, got string
Schema check passed

Real projects use schema libraries (Ajv for JSON Schema, Zod) for this, but they rely on exactly these type checks.


📝 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 typeof result for "42", 42, 42n, [42] and { n: 42 }.

Show answer

📄 practice1.js

console.log(typeof "42");
console.log(typeof 42);
console.log(typeof 42n);
console.log(typeof [42]);
console.log(typeof { n: 42 });

🖥️ Output

string
number
bigint
object
object

Q2. Write a function isPlainObject(value) that returns true only for objects like {}, and false for null, arrays and primitives.

Show answer

📄 practice2.js

function isPlainObject(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

console.log(isPlainObject({ a: 1 }));
console.log(isPlainObject(null));
console.log(isPlainObject([1, 2]));
console.log(isPlainObject("text"));

🖥️ Output

true
false
false
false

Q3. Predict the output, then run it.

const cart = { items: 2 };
const saved = cart;
saved.items = 5;
let count = cart.items;
count = 10;
console.log(cart.items, saved.items, count);
Show answer

📄 practice3.js

const cart = { items: 2 };
const saved = cart;
saved.items = 5;
let count = cart.items;
count = 10;
console.log(cart.items, saved.items, count);

🖥️ Output

5 5 10

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.

Show answer

📄 practice4.js

const template = { name: "asha", tags: ["ui"] };
const user = structuredClone(template);
user.tags.push("api");

console.log("template:", template.tags);
console.log("copy:", user.tags);

🖥️ Output

template: [ 'ui' ]
copy: [ 'ui', 'api' ]

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.

  1. How many data types does JavaScript have?
  2. What is typeof null?
  3. What is typeof [1, 2, 3]?
  4. What is typeof NaN?
  5. Which value is not a primitive?
  6. After const a = { n: 1 }; const b = a; b.n = 2;, what is a.n?
  7. What does { id: 1 } === { id: 1 } return?
  8. What does JSON.stringify({ a: undefined, b: null }) return?
  9. Which creates an independent deep copy of an object?
  10. What is the result of Symbol("id") === Symbol("id")?

💼 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?

📄 check.js

const check = (v) =>
  v === null ? "null"
  : Array.isArray(v) ? "array"
  : typeof v === "object" ? "object"
  : typeof v;

console.log(check(null), check([]), check({}), check(5));

⌨️ Terminal

node check.js

🖥️ Output

null array object number

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.

Next, continue with Lesson 8: Type Conversion and Coercion. For extra practice, solve the JavaScript data types practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Operators: Arithmetic, Assignment, Comparison, Logical and More

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.
  • + also joins strings, as you saw in the Type Conversion lesson.

📄 remainder.js

const seconds = 3725;
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = seconds % 60;
console.log(`${seconds}s = ${h}h ${m}m ${s}s`);

for (let n = 1; n <= 4; n++) {
  console.log(n, n % 2 === 0 ? "even" : "odd");
}

⌨️ Terminal

node remainder.js

🖥️ Output

3725s = 1h 2m 5s
1 odd
2 even
3 odd
4 even

🔼 Increment and Decrement (++ and –)

++ adds 1 and -- subtracts 1. The position matters when you use the result in the same expression:

  • Postfix x++: returns the old value, then increments.
  • Prefix ++x: increments first, then returns the new value.

📄 increment.js

let count = 5;
console.log(count++);   // returns 5, then count becomes 6
console.log(count);
console.log(++count);   // count becomes 7, returns 7
console.log(count--);   // returns 7, then count becomes 6
console.log(count);

⌨️ Terminal

node increment.js

🖥️ Output

5
6
7
7
6

💡 Tip: On its own line (count++;) prefix and postfix behave the same. Avoid using ++ inside larger expressions; count += 1 on its own line is clearer.


📝 Assignment Operators

= assigns a value. Compound assignment operators combine an operation with assignment:

OperatorExampleSame as
+=x += 5x = x + 5
-=x -= 2x = x - 2
*=x *= 3x = x * 3
/=x /= 2x = x / 2
%=x %= 3x = x % 3
**=x **= 2x = x ** 2
??=, ||=, &&=x ??= 1Logical assignment (see the previous lesson)

📄 assignment.js

let total = 100;
total += 50;   // 150
total -= 20;   // 130
total *= 2;    // 260
total /= 4;    // 65
total %= 10;   // 5
total **= 3;   // 125
console.log(total);

let report = "Results:";
report += " 18 passed,";
report += " 2 failed";
console.log(report);

⌨️ Terminal

node assignment.js

🖥️ Output

125
Results: 18 passed, 2 failed

⚖️ Comparison Operators

Comparison operators return true or false:

OperatorMeaningExample (true)
===Strictly equal (same type and value)200 === 200
!==Strictly not equal"200" !== 200
== / !=Loosely equal / not equal (with coercion)Avoid; see the Equality lesson
> <Greater / less than5 > 3
>= <=Greater / less than or equal3 <= 3

📄 comparison.js

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

OperatorNameResult
a && bANDIf a is falsy, returns a; otherwise returns b
a || bORIf a is truthy, returns a; otherwise returns b
!aNOTtrue if a is falsy, otherwise false
a ?? bNullish coalescingb 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 operator condition ? 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);

⌨️ Terminal

node keyword-ops.js

🖥️ Output

string
true
true
true false
true false
{ name: 'Asha' }
  • 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.

📄 spread.js

const smoke = ["login", "search"];
const regression = [...smoke, "checkout", "refund"];
console.log(regression);
console.log(Math.max(...[12, 99, 45]));

const defaults = { browser: "chromium", headless: true };
const config = { ...defaults, headless: false };
console.log(config);

⌨️ Terminal

node spread.js

🖥️ Output

[ 'login', 'search', 'checkout', 'refund' ]
99
{ browser: 'chromium', headless: false }

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).

OrderOperators
1 (highest)( ) grouping
2?., member access . [ ], function call ( ), new
3Postfix x++ x--
4Unary ! - + ++x typeof delete
5**
6* / %
7+ -
8< > <= >= in instanceof
9=== !== == !=
10&&
11|| ??
12? :
13 (lowest)Assignment = += … and the comma ,

📄 precedence.js

console.log(2 + 3 * 4);          // * first: 14
console.log((2 + 3) * 4);        // grouping first: 20
console.log(2 ** 3 ** 2);        // right to left: 2 ** 9 = 512
console.log(10 - 4 - 3);         // left to right: 3
console.log(true || false && false); // && first: true
console.log(!0 + 1);             // !0 is true, true + 1 = 2

⌨️ Terminal

node precedence.js

🖥️ Output

14
20
512
3
true
2

💡 Tip: You do not need to memorise the table. When in doubt, add parentheses: (price * qty) + shipping is clear to every reader.


📝 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 total price of 3 items at 249.5 each, plus 18% tax, rounded to two decimals.

Show answer

📄 practice1.js

const subtotal = 3 * 249.5;
const total = subtotal + subtotal * 0.18;
console.log(total.toFixed(2));

🖥️ Output

883.23

Q2. Predict the output, then run it.

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).

Show answer

📄 practice4.js

const passed = (status, ms) => (status === 200 && ms < 2000) || status === 304;

console.log(passed(200, 1500));
console.log(passed(200, 2500));
console.log(passed(304, 3000));

🖥️ Output

true
false
true

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.

  1. What is 17 % 5?
  2. What is 2 ** 3?
  3. After let a = 5; const b = a++;, what are a and b?
  4. What does "" || "guest" return?
  5. What does "a" && "b" return?
  6. In x > 0 && save(), when is save() called?
  7. What is 2 + 3 * 4?
  8. What is 2 ** 3 ** 2?
  9. Which operator checks if a property name exists in an object?
  10. What does score >= 50 ? "pass" : "fail" return when score is 50?

💼 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.

📄 returns.js

console.log("a" && 0, null || "x", !!("a" && "b"));

⌨️ Terminal

node returns.js

🖥️ Output

0 x true

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}`.

📄 precedence-bug.js

const price = 100, tax = 20;
console.log("Total: " + price + tax);
console.log("Total: " + (price + tax));

⌨️ Terminal

node precedence-bug.js

🖥️ Output

Total: 10020
Total: 120

❓ Frequently Asked Questions

🤔 What are the types of operators in JavaScript?

Arithmetic (+ - * / % **), assignment (= += -= …), comparison (=== !== > <), logical (&& || ! ??), the conditional (ternary) operator, and special operators such as typeof, instanceof, in, delete, spread and comma.

🤔 What does the % operator do in JavaScript?

It returns the remainder of a division. 10 % 3 is 1. It is commonly used to test even or odd numbers and to wrap values around.

🤔 Is there an integer division operator?

No. / always produces a decimal result. Use Math.floor(a / b) (or Math.trunc for negative numbers) to get the whole-number part.

🤔 What is the ?: operator called?

The conditional operator, usually called the ternary operator because it takes three operands: condition ? a : b.


🏁 Summary

  • Arithmetic: + - * / % **; / never rounds and % gives the remainder.
  • x++ returns the old value, ++x the new one; compound assignment (+= …) updates in place.
  • Comparisons return booleans; use === and !==.
  • && and || short-circuit and return an operand value; the ternary picks between two values.
  • typeof, instanceof, in, delete and spread are operators too; use parentheses when precedence is unclear.

Next, continue with Lesson 13: if, else if, else. For extra practice, solve the JavaScript operators practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Variables: var, let and const Explained with Examples

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:

constletvar
Can be reassignedNoYesYes
Must be initialisedYesNoNo
ScopeBlockBlockFunction
Can be redeclared in the same scopeNoNoYes
Use before declarationReferenceError (TDZ)ReferenceError (TDZ)undefined
Introduced inES2015ES2015ES1 (1997)

let declares a variable whose value can change:

📄 let.js

let score = 0;
score = score + 10;
score += 5;          // shorthand for score = score + 5
console.log("Score:", score);

⌨️ Terminal

node let.js

🖥️ Output

Score: 15

const declares a constant binding: the name cannot be pointed at a new value. Trying to reassign it throws a TypeError:

📄 const.js

const BASE_URL = "https://sqatools.in";
console.log(BASE_URL);

BASE_URL = "https://example.com";

⌨️ Terminal

node const.js

🖥️ Output

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);

⌨️ Terminal

node const-object.js

🖥️ Output

{ name: 'Asha', role: 'lead' }
[ 'smoke', 'regression' ]

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 one i 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

  1. Use const by default.
  2. Switch to let only when the variable must be reassigned (counters, totals, values that change in a loop).
  3. 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.

Show answer

📄 practice1.js

const COURSE = "JavaScript";
let lesson = 1;
lesson = 6;
console.log(`${COURSE} lesson ${lesson}`);

🖥️ Output

JavaScript lesson 6

Q2. Predict the output, then run it.

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.

📄 practice4.js

const tags = ["ui"];
tags.push("api");
console.log(tags);

🖥️ Output

[ 'ui', 'api' ]

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.

  1. Which keyword should you use by default for a new variable?
  2. What happens with const x = 1; x = 2;?
  3. Is this allowed?
    const list = [1];
    list.push(2);
  4. What is the scope of a var declared inside an if block in a function?
  5. What does this print?
    console.log(x);
    var x = 5;
  6. What does this throw?
    console.log(y);
    let y = 5;
  7. What does let a = 1; let a = 2; in the same scope cause?
  8. Why does a for (var i...) loop with setTimeout print 3, 3, 3?
  9. Which declaration is invalid?
  10. What is globalThis?

💼 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.

📄 freeze.js

const config = Object.freeze({ retries: 2 });
config.retries = 5;          // ignored outside strict mode
console.log(config.retries);

⌨️ Terminal

node freeze.js

🖥️ Output

2

Q5. Predict the output and explain it.

📄 interview-loop.js

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.

Next, continue with Lesson 7: Data Types. For extra practice, solve the JavaScript variables practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in