JavaScript break, continue and Labels: Control Loops with Examples

Loops normally run until their condition becomes false. Often you want to stop earlier, for example as soon as you find the failing row, or skip items you do not care about, such as disabled tests. break and continue give you that control, and labels extend it to nested loops. In this lesson you will learn all three, why they do not work inside forEach, and the array methods that replace them.

📖 What You’ll Learn: break to exit a loop, continue to skip an iteration, break in while loops and switch, labeled statements for nested loops, why break and continue fail inside forEach, the alternatives some, every and find, and how to write clear early-exit loops.


⛔ break: Exit a Loop Early

Definition: the break statement immediately ends the innermost loop (or switch) it is in. Execution continues with the first statement after the loop.

📄 break.js

const rows = ["ok", "ok", "ERROR", "ok", "ok"];

for (let i = 0; i < rows.length; i++) {
  console.log(`checking row ${i}: ${rows[i]}`);
  if (rows[i] === "ERROR") {
    console.log(`first error found at row ${i}, stopping`);
    break;
  }
}
console.log("after the loop");

⌨️ Terminal

node break.js

🖥️ Output

checking row 0: ok
checking row 1: ok
checking row 2: ERROR
first error found at row 2, stopping
after the loop

Rows 3 and 4 are never checked. Stopping as soon as you have your answer saves time, which matters when each iteration is a slow network call or a page action.


⏭️ continue: Skip to the Next Iteration

Definition: the continue statement ends the current iteration and jumps to the next one. In a for loop the update step (i++) still runs.

📄 continue.js

const tests = [
  { name: "login", skip: false },
  { name: "legacy export", skip: true },
  { name: "search", skip: false },
  { name: "old report", skip: true },
  { name: "checkout", skip: false },
];

let ran = 0;
for (const test of tests) {
  if (test.skip) {
    console.log(`skipped: ${test.name}`);
    continue;
  }
  ran++;
  console.log(`running: ${test.name}`);
}
console.log(`${ran} tests ran`);

⌨️ Terminal

node continue.js

🖥️ Output

running: login
skipped: legacy export
running: search
skipped: old report
running: checkout
3 tests ran

💡 Tip: continue works like a guard clause inside a loop: handle the cases you want to skip at the top, and keep the main logic un-indented below.


🔄 break and continue in while Loops

Both statements work in while and do...while too. A common pattern is while (true) with a break when a goal is reached, plus a safety limit:

📄 while-break.js

let attempt = 0;
const MAX = 10;

while (true) {
  attempt++;
  if (attempt > MAX) {
    console.log("giving up");
    break;
  }
  if (attempt % 2 === 1) {
    console.log(`attempt ${attempt}: odd, skipping`);
    continue;
  }
  console.log(`attempt ${attempt}: checking...`);
  if (attempt === 4) {
    console.log("success on attempt", attempt);
    break;
  }
}

⌨️ Terminal

node while-break.js

🖥️ Output

attempt 1: odd, skipping
attempt 2: checking...
attempt 3: odd, skipping
attempt 4: checking...
success on attempt 4

⚠️ Watch out: In a while loop, make sure the variable the condition depends on is updated before any continue. If attempt++ were placed after the continue, the loop would never advance and would run forever.


🏷️ Labels: break and continue in Nested Loops

In nested loops, break and continue affect only the innermost loop. To control an outer loop, give it a label (a name followed by a colon) and use break label or continue label.

📄 labels.js

const grid = [
  ["A1", "A2", "A3"],
  ["B1", "XX", "B3"],
  ["C1", "C2", "C3"],
];

// Without a label: break only exits the inner loop
for (const row of grid) {
  for (const cell of row) {
    if (cell === "XX") break;
    console.log("inner-only:", cell);
  }
}

// With a label: break exits both loops
search: for (const row of grid) {
  for (const cell of row) {
    if (cell === "XX") {
      console.log("found XX, stopping the whole search");
      break search;
    }
    console.log("labeled:", cell);
  }
}

⌨️ Terminal

node labels.js

🖥️ Output

inner-only: A1
inner-only: A2
inner-only: A3
inner-only: B1
inner-only: C1
inner-only: C2
inner-only: C3
labeled: A1
labeled: A2
labeled: A3
labeled: B1
found XX, stopping the whole search

continue label skips to the next iteration of the labeled (outer) loop:

📄 continue-label.js

const suites = {
  smoke: ["login", "BLOCKED", "search"],
  cart: ["add item", "remove item"],
};

suites: for (const [suite, tests] of Object.entries(suites)) {
  for (const test of tests) {
    if (test === "BLOCKED") {
      console.log(`${suite}: blocked test found, skipping rest of suite`);
      continue suites;
    }
    console.log(`${suite}: ${test}`);
  }
}

⌨️ Terminal

node continue-label.js

🖥️ Output

smoke: login
smoke: blocked test found, skipping rest of suite
cart: add item
cart: remove item

💡 Tip: Labels are rare in everyday code. If you need one, consider moving the inner loop into a function and using return, which is often easier to read.


🚫 break and continue Do Not Work in forEach

forEach calls a function for each item. break and continue belong to loops, not functions, so using them inside the callback is a syntax error:

📄 foreach-break.js

const ids = [1, 2, 3];
ids.forEach((id) => {
  if (id === 2) break;
  console.log(id);
});

⌨️ Terminal

node foreach-break.js

🖥️ Output

/home/you/js-course/foreach-break.js:3
  if (id === 2) break;
                ^^^^^

SyntaxError: Illegal break statement

Node.js v26.13.0

return inside the callback only ends that one call, so it behaves like continue, never like break:

📄 foreach-return.js

[1, 2, 3, 4].forEach((n) => {
  if (n === 2) return;   // skips 2 only; the loop goes on
  console.log(n);
});

⌨️ Terminal

node foreach-return.js

🖥️ Output

1
3
4

🔎 Alternatives: some, every and find

Many loops with break are really searches. These array methods stop early for you and express the intent better:

MethodReturnsStops when
arr.find(fn)The first matching item, or undefinedThe callback returns truthy
arr.findIndex(fn)Its index, or -1The callback returns truthy
arr.some(fn)true if at least one item matchesThe callback returns truthy
arr.every(fn)true if all items matchThe callback returns falsy
arr.includes(v)true if the value is presentThe value is found

📄 alternatives.js

const results = [
  { test: "login", status: "passed", ms: 800 },
  { test: "search", status: "failed", ms: 1200 },
  { test: "cart", status: "passed", ms: 4300 },
];

const firstFailure = results.find((r) => r.status === "failed");
console.log("first failure:", firstFailure?.test);

console.log("any failed?", results.some((r) => r.status === "failed"));
console.log("all under 5s?", results.every((r) => r.ms < 5000));
console.log("slow test index:", results.findIndex((r) => r.ms > 3000));

⌨️ Terminal

node alternatives.js

🖥️ Output

first failure: search
any failed? true
all under 5s? true
slow test index: 2

The same “first failure” search written with a loop and break, for comparison:

📄 loop-vs-method.js

const statuses = ["passed", "failed", "passed"];
let firstFailedIndex = -1;
for (let i = 0; i < statuses.length; i++) {
  if (statuses[i] === "failed") {
    firstFailedIndex = i;
    break;
  }
}
console.log(firstFailedIndex, statuses.findIndex((s) => s === "failed"));

⌨️ Terminal

node loop-vs-method.js

🖥️ Output

1 1

🧪 Tester Scenario: Scan a Log for the First Fatal Error

This script walks through log lines, ignores debug noise with continue, counts warnings, and stops at the first fatal error with break:

📄 scan-log.js

const log = [
  "DEBUG cache warmed",
  "INFO  server started on :3000",
  "WARN  slow query 1200ms",
  "DEBUG user lookup",
  "WARN  retrying payment gateway",
  "FATAL database connection lost",
  "INFO  shutting down",
];

let warnings = 0;
let fatal = null;

for (const [lineNo, line] of log.entries()) {
  if (line.startsWith("DEBUG")) continue;     // ignore noise
  if (line.startsWith("WARN")) warnings++;
  if (line.startsWith("FATAL")) {
    fatal = { lineNo: lineNo + 1, line };
    break;                                    // nothing after this matters
  }
}

console.log(`warnings before failure: ${warnings}`);
console.log(fatal ? `first fatal at line ${fatal.lineNo}: ${fatal.line}` : "no fatal errors");

⌨️ Terminal

node scan-log.js

🖥️ Output

warnings before failure: 2
first fatal at line 6: FATAL database connection lost

📝 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 numbers from 1 to 20, but stop as soon as you reach the first number divisible by both 3 and 4.

Show answer

📄 practice1.js

for (let n = 1; n <= 20; n++) {
  console.log(n);
  if (n % 3 === 0 && n % 4 === 0) break;
}

🖥️ Output

1
2
3
4
5
6
7
8
9
10
11
12

Q2. Print only the odd numbers from 1 to 10 using continue.

Show answer

📄 practice2.js

for (let n = 1; n <= 10; n++) {
  if (n % 2 === 0) continue;
  console.log(n);
}

🖥️ Output

1
3
5
7
9

Q3. Sum the valid numbers in ["5", "abc", "12", "", "8"], skipping values that are not numbers or are empty.

Show answer

📄 practice3.js

const raw = ["5", "abc", "12", "", "8"];
let sum = 0;
for (const value of raw) {
  if (value.trim() === "") continue;
  const n = Number(value);
  if (!Number.isFinite(n)) continue;
  sum += n;
}
console.log(sum);

🖥️ Output

25

Q4. Find the coordinates of the first negative number in [[3, 5], [7, -2], [-9, 1]] and stop searching once found, using a labeled break.

Show answer

📄 practice4.js

const matrix = [[3, 5], [7, -2], [-9, 1]];
let found = null;

outer: for (let r = 0; r < matrix.length; r++) {
  for (let c = 0; c < matrix[r].length; c++) {
    if (matrix[r][c] < 0) {
      found = [r, c];
      break outer;
    }
  }
}
console.log(found);

🖥️ Output

[ 1, 1 ]

Q5. Rewrite this loop using some().

let hasAdmin = false;
for (const u of users) {
  if (u.role === "admin") {
    hasAdmin = true;
    break;
  }
}
Show answer

📄 practice5.js

const users = [{ role: "tester" }, { role: "admin" }, { role: "dev" }];
const hasAdmin = users.some((u) => u.role === "admin");
console.log(hasAdmin);

🖥️ Output

true

Q6. This code never ends. Explain why and fix it.

let i = 0;
while (i < 5) {
  if (i === 2) continue;
  console.log(i);
  i++;
}
Show answer

When i is 2, continue jumps back to the condition before i++ runs, so i stays 2 forever. Increment before the continue:

📄 practice6.js

let i = 0;
while (i < 5) {
  i++;
  if (i === 3) continue;   // skip the third value
  console.log(i);
}

🖥️ Output

1
2
4
5

🧠 MCQ Quiz: break, continue and Labels

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 does break do inside a loop?
  2. What does continue do?
  3. What is printed?
    for (let i = 0; i < 5; i++) {
      if (i === 3) break;
      console.log(i);
    }
  4. What is printed?
    for (let i = 0; i < 5; i++) {
      if (i === 3) continue;
      console.log(i);
    }
  5. In nested loops, which loop does a plain break exit?
  6. How do you exit both loops at once?
  7. What happens with break inside a forEach callback?
  8. What does return inside a forEach callback do?
  9. Which method returns the first item that matches a condition?
  10. Why can a continue in a while loop cause an infinite loop?

💼 Interview Questions and Answers

Q1. What is the difference between break and continue?

break terminates the whole loop (or switch) and moves on to the code after it. continue terminates only the current iteration and moves to the next one: in a for loop it runs the update expression, in while it re-checks the condition. Both affect only the innermost loop unless a label is used.

Q2. How do you break out of a forEach loop?

You cannot; break is a syntax error there and return only skips the current item. Use a for...of loop with break, or a method that stops early by design: some, every, find, findIndex. Throwing an exception to stop forEach works but is a bad practice.

Q3. What are labeled statements in JavaScript?

A label is an identifier followed by a colon placed before a statement, usually a loop: outer: for (...). break outer exits that loop and continue outer jumps to its next iteration, from inside nested loops. They are valid but uncommon; extracting the nested loop into a function with return is often clearer.

Q4. Write code to check whether every API response in a list returned status 200, stopping at the first failure.

📄 every.js

const responses = [{ url: "/a", status: 200 }, { url: "/b", status: 500 }, { url: "/c", status: 200 }];

let checked = 0;
const allOk = responses.every((r) => {
  checked++;
  return r.status === 200;
});
console.log({ allOk, checked });
console.log("first failure:", responses.find((r) => r.status !== 200)?.url);

⌨️ Terminal

node every.js

🖥️ Output

{ allOk: false, checked: 2 }
first failure: /b

every stops at /b, so only two responses are checked. find then reports which one failed.


❓ Frequently Asked Questions

🤔 Can I use break in an if statement?

Only if the if is inside a loop or switch; then break exits that loop or switch. A break in an if outside any loop is a syntax error (unless it targets a labeled block).

🤔 Is using break considered bad practice?

No. Stopping a search as soon as you have the answer is good practice. Prefer array methods like find or some when they express the intent more directly.

🤔 Does break work in for…of and for…in loops?

Yes. break and continue work in every loop statement: for, for...of, for...in, while and do...while.

🤔 What is the difference between break and return?

break leaves the current loop or switch; return leaves the whole function (and therefore any loop inside it) and can send back a value.


🏁 Summary

  • break exits the innermost loop or switch; continue skips to the next iteration.
  • Labels (outer: for ...) let break outer and continue outer control outer loops.
  • In while loops, update the loop variable before any continue to avoid infinite loops.
  • break/continue cannot be used in forEach; return there only skips one item.
  • For searches, find, findIndex, some and every stop early and read better.

Next, continue with Lesson 17: Functions. This completes Module 3. Module 4 starts with functions, the building blocks of every program and test.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Truthy and Falsy Values, == vs === and Object.is

Every if statement, every loop condition and every assertion depends on two questions: “is this value true enough?” and “are these two values equal?”. JavaScript answers both with rules that surprise people coming from other languages: an empty array is true, "0" == 0 is true, and { id: 1 } is not equal to { id: 1 }. In this lesson you will learn those rules, the safe habits that avoid the traps, and how to compare objects and arrays properly in tests.

📖 What You’ll Learn: the eight falsy values, truthy values that surprise people, Boolean() and the double NOT (!!), how conditions use truthiness, loose equality == and its coercion rules, strict equality ===, Object.is, comparing objects and arrays by reference and deeply, comparing strings, and common equality bugs in tests.


🌗 Truthy and Falsy Values

Definition: wherever JavaScript expects a boolean (in if, while, &&, ||, ! and the ? : operator), it converts the value to true or false. Values that become false are falsy; every other value is truthy.

There are exactly eight falsy values:

Falsy valueType
falseboolean
0 and -0number
0nbigint
"" (empty string)string
nullnull
undefinedundefined
NaNnumber

Everything else is truthy, including several values that look “empty”:

📄 truthy.js

const surprises = [
  ["\"0\"", "0"], ["\"false\"", "false"], ["\" \"", " "], ["[]", []],
  ["{}", {}], ["-1", -1], ["Infinity", Infinity], ["new Date(0)", new Date(0)],
];
for (const [label, value] of surprises) {
  console.log(`${label.padEnd(12)} is ${value ? "truthy" : "falsy"}`);
}

⌨️ Terminal

node truthy.js

🖥️ Output

"0"          is truthy
"false"      is truthy
" "          is truthy
[]           is truthy
{}           is truthy
-1           is truthy
Infinity     is truthy
new Date(0)  is truthy

⚠️ Watch out: An empty array [] and an empty object {} are truthy. To check for “no items”, test the length: if (results.length === 0), or Object.keys(obj).length === 0 for objects.


🔁 Boolean() and the Double NOT (!!)

To get the actual boolean, use Boolean(value) or !!value. The first ! converts and negates, the second negates back.

📄 boolean.js

const username = "asha";
const token = "";
const retries = 0;

console.log(Boolean(username), !!username);
console.log(Boolean(token), !!token);
console.log(!retries);          // single ! : "is retries falsy?"

const hasItems = !![1, 2].length;
console.log({ hasItems });

⌨️ Terminal

node boolean.js

🖥️ Output

true true
false false
true
{ hasItems: true }

🚦 Truthiness in Conditions (and the 0 Trap)

Short checks such as if (name) are idiomatic JavaScript, and they read well:

📄 condition.js

function greet(name) {
  if (name) {
    return `Hello, ${name}!`;
  }
  return "Hello, guest!";
}

console.log(greet("Asha"));
console.log(greet(""));
console.log(greet(undefined));

⌨️ Terminal

node condition.js

🖥️ Output

Hello, Asha!
Hello, guest!
Hello, guest!

But truthiness treats a real value of 0 or "" as “missing”. This bug appears constantly with quantities, prices and scores:

📄 zero-trap.js

function describeStock(qty) {
  if (!qty) return "stock unknown";   // bug: 0 is a real stock level
  return `${qty} in stock`;
}
console.log(describeStock(5), "|", describeStock(0), "|", describeStock(undefined));

function describeStockFixed(qty) {
  if (qty === undefined || qty === null) return "stock unknown";
  return `${qty} in stock`;
}
console.log(describeStockFixed(5), "|", describeStockFixed(0), "|", describeStockFixed(undefined));

⌨️ Terminal

node zero-trap.js

🖥️ Output

5 in stock | stock unknown | stock unknown
5 in stock | 0 in stock | stock unknown

💡 Tip: Use a truthiness check when “empty” and “missing” mean the same thing (an empty search term). Use an explicit comparison when 0, "" or false are valid values. The next lesson shows ??, which was designed for exactly this.


⚖️ Loose Equality (==) vs Strict Equality (===)

Definition: strict equality === returns true only when both values have the same type and the same value. Loose equality == first converts the values to a common type (coercion) and then compares. !== and != are their opposites.

📄 equality.js

console.log("1" == 1, "1" === 1);
console.log(0 == "", 0 === "");
console.log(0 == false, 0 === false);
console.log("" == false, "" === false);
console.log(null == undefined, null === undefined);
console.log(null == 0, null >= 0);    // a famous inconsistency
console.log(NaN == NaN, NaN === NaN);
console.log([1] == 1, [1, 2] == "1,2");

⌨️ Terminal

node equality.js

🖥️ Output

true false
true false
true false
true false
true false
false true
false false
true true

The loose rules, simplified:

  1. If the types are the same, compare like ===.
  2. null and undefined are equal to each other and to nothing else.
  3. Otherwise, booleans become numbers, strings become numbers when compared with numbers, and objects are converted to primitives.
Comparison=====
"5" vs 5truefalse
0 vs ""truefalse
0 vs falsetruefalse
null vs undefinedtruefalse
null vs 0falsefalse
NaN vs NaNfalsefalse

💡 Tip: Always use === and !==. The single accepted exception is value == null, a short way to test for null or undefined. ESLint’s eqeqeq rule enforces this.


🔍 Object.is: The Strictest Comparison

Object.is(a, b) is like === with two differences: it treats NaN as equal to NaN, and it distinguishes 0 from -0.

📄 object-is.js

console.log(NaN === NaN, Object.is(NaN, NaN));
console.log(0 === -0, Object.is(0, -0));
console.log(Object.is("qa", "qa"), Object.is({}, {}));

⌨️ Terminal

node object-is.js

🖥️ Output

false true
true false
true false

You rarely need it in everyday code, but testing frameworks use it: Jest’s and Playwright’s toBe() compare with Object.is.


📦 Comparing Objects and Arrays

Objects and arrays are compared by reference: === is true only if both sides are the very same object, even when the contents are identical.

📄 objects-equal.js

const expected = { id: 1, tags: ["smoke"] };
const actual = { id: 1, tags: ["smoke"] };

console.log(expected === actual);          // different objects
console.log(expected == actual);           // also false
console.log(JSON.stringify(expected) === JSON.stringify(actual)); // quick content check

⌨️ Terminal

node objects-equal.js

🖥️ Output

false
false
true

Comparing JSON strings is fragile because property order matters ({a:1,b:2} and {b:2,a:1} give different strings). For real tests use a deep equality assertion, which compares the contents recursively:

📄 deep-equal.js

const assert = require("node:assert/strict");

const expected = { id: 1, name: "Asha", tags: ["smoke", "ui"] };
const actual = { name: "Asha", id: 1, tags: ["smoke", "ui"] };   // different key order

assert.deepStrictEqual(actual, expected);
console.log("deep equality passed");

const changed = { ...actual, tags: ["smoke"] };
try {
  assert.deepStrictEqual(changed, expected);
} catch (err) {
  console.log(err.message.split("\n").slice(0, 1).join(""));
}

⌨️ Terminal

node deep-equal.js

🖥️ Output

deep equality passed
Expected values to be strictly deep-equal:

📌 Note: In Playwright and Jest: expect(a).toBe(b) checks identity (Object.is), while expect(a).toEqual(b) and toStrictEqual(b) check deep equality. Using toBe on two objects with the same content fails, which confuses many beginners.


🔤 Comparing Strings

Strings are compared character by character using their Unicode code values. That means uppercase letters sort before lowercase letters, and numbers stored as strings compare alphabetically:

📄 strings-compare.js

console.log("apple" < "banana");     // true
console.log("Zebra" < "apple");      // true: uppercase codes are smaller
console.log("10" < "9");             // true: compares "1" with "9"

console.log("Asha" === "asha");
console.log("Asha".toLowerCase() === "asha".toLowerCase()); // case-insensitive
console.log("résumé".localeCompare("resume", "en", { sensitivity: "base" }) === 0);
console.log("  ok ".trim() === "ok");

⌨️ Terminal

node strings-compare.js

🖥️ Output

true
true
true
false
true
true
true

💡 Tip: Text from web pages often has extra spaces, line breaks or different case. Normalise both sides (trim(), toLowerCase()) before comparing, or use matchers designed for UI text such as Playwright’s toHaveText, which ignores extra whitespace.


🧪 Tester Scenario: Write a Safe Comparison Helper

This helper compares an expected and an actual value the way a test should: strict for primitives, deep for objects, with a readable result.

📄 check.js

const { isDeepStrictEqual } = require("node:util");

function check(label, actual, expected) {
  const ok = typeof expected === "object" && expected !== null
    ? isDeepStrictEqual(actual, expected)
    : Object.is(actual, expected);
  console.log(`${ok ? "PASS" : "FAIL"} ${label}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
  return ok;
}

const response = { status: 200, count: "3", items: ["a", "b", "c"], error: null };

check("status", response.status, 200);
check("count", response.count, 3);                  // string vs number: caught
check("count as number", Number(response.count), 3);
check("items", response.items, ["a", "b", "c"]);
check("error", response.error, null);

⌨️ Terminal

node check.js

🖥️ Output

PASS status: expected 200, got 200
FAIL count: expected 3, got "3"
PASS count as number: expected 3, got 3
PASS items: expected ["a","b","c"], got ["a","b","c"]
PASS error: expected null, got null

The second check fails on purpose: the API sent "3" (a string) where a number was expected. With ==, this defect would have passed unnoticed.


📝 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 isEmpty(value) that returns true for null, undefined, "", [] and {}, and false for 0, false, "a" and [1].

Show answer

📄 practice1.js

function isEmpty(value) {
  if (value === null || value === undefined) return true;
  if (typeof value === "string" || Array.isArray(value)) return value.length === 0;
  if (typeof value === "object") return Object.keys(value).length === 0;
  return false;
}

for (const v of [null, undefined, "", [], {}, 0, false, "a", [1]]) {
  console.log(JSON.stringify(v) ?? "undefined", isEmpty(v));
}

🖥️ Output

null true
undefined true
"" true
[] true
{} true
0 false
false false
"a" false
[1] false

Q2. Predict each result, then run the code: "" == 0, "0" == false, [] == false, null == false, undefined == null.

Show answer

📄 practice2.js

console.log("" == 0);
console.log("0" == false);
console.log([] == false);
console.log(null == false);
console.log(undefined == null);

🖥️ Output

true
true
true
false
true

null is only loosely equal to undefined, so null == false is false. [] == false converts [] to "" and then to 0.

Q3. Fix the bug: a discount of 0% should print Discount: 0%, but it prints No discount.

function showDiscount(percent) {
  return percent ? `Discount: ${percent}%` : "No discount";
}
console.log(showDiscount(0));
Show answer

📄 practice3.js

function showDiscount(percent) {
  return percent === undefined || percent === null ? "No discount" : `Discount: ${percent}%`;
}
console.log(showDiscount(0));
console.log(showDiscount(undefined));

🖥️ Output

Discount: 0%
No discount

Q4. Compare the arrays [1, 2, 3] and [1, 2, 3] so the result is true using node:util.

Show answer

📄 practice4.js

const { isDeepStrictEqual } = require("node:util");
console.log([1, 2, 3] === [1, 2, 3]);
console.log(isDeepStrictEqual([1, 2, 3], [1, 2, 3]));

🖥️ Output

false
true

Q5. A page shows the heading " Welcome, ASHA \n". Check whether it matches the expected text "Welcome, Asha", ignoring case and extra whitespace.

Show answer

📄 practice5.js

const actual = "  Welcome, ASHA \n";
const expected = "Welcome, Asha";
const normalise = (s) => s.trim().replace(/\s+/g, " ").toLowerCase();
console.log(normalise(actual) === normalise(expected));

🖥️ Output

true

Q6. Write isMissing(value) in one line that returns true only for null and undefined.

Show answer

📄 practice6.js

const isMissing = (value) => value == null;

console.log(isMissing(null), isMissing(undefined), isMissing(0), isMissing(""));

🖥️ Output

true true false false

This is the one place where == is commonly accepted, because null is loosely equal only to undefined. value === null || value === undefined is the explicit equivalent.


🧠 MCQ Quiz: Truthy, Falsy and Equality

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 falsy values does JavaScript have?
  2. Which value is truthy?
  3. What is "1" == 1?
  4. What is "1" === 1?
  5. What is null == undefined?
  6. What is NaN === NaN?
  7. What is { a: 1 } === { a: 1 }?
  8. Which assertion should you use to compare two objects by content in Playwright or Jest?
  9. What does !!"false" return?
  10. What is "10" < "9"?

💼 Interview Questions and Answers

Q1. What is the difference between == and ===?

=== (strict equality) compares type and value without conversion. == (loose equality) converts the operands to a common type first, which leads to results such as 0 == "" and "0" == false being true. Use === by default; the only common exception is x == null to check for both null and undefined.

Q2. List the falsy values in JavaScript.

false, 0, -0, 0n, "", null, undefined and NaN (plus the legacy browser object document.all). Everything else is truthy, including "0", "false", [], {} and negative numbers.

Q3. How do you compare two objects or arrays for equality?

With === you only learn whether they are the same reference. To compare contents, use a deep-equality function: assert.deepStrictEqual or util.isDeepStrictEqual in Node.js, toEqual/toStrictEqual in Jest and Playwright, or a library such as Lodash’s isEqual. JSON.stringify comparison is a fragile shortcut because key order and undefined values affect it.

Q4. Explain why null >= 0 is true but null == 0 is false.

Relational operators (>=, <) convert null to the number 0, so 0 >= 0 is true. Equality == has a special rule: null is only loosely equal to undefined, so it is never converted to 0 there. It shows why mixing loose comparisons with nullable values is risky.

Q5. A test checks if (response.data) before asserting, and the test still passes when the API returns no data. What is wrong?

An empty array is truthy, so the block runs but may assert nothing useful; and if data is 0, "", null or missing, the block is skipped and the test passes without checking anything. Conditional assertions hide defects. Assert unconditionally on what you expect (expect(response.data).toEqual([...]) or expect(response.data.length).toBeGreaterThan(0)), so a missing or wrong value fails the test.


❓ Frequently Asked Questions

🤔 Should I always use === in JavaScript?

Yes, as a rule. It is predictable and catches type mismatches. Use x == null only if your team accepts it as shorthand for “null or undefined”.

🤔 Why is [] == false true but [] is truthy?

They use different rules. In a condition, every object is truthy. With ==, the array is converted to a primitive ("") and then to a number (0), and false also becomes 0.

🤔 How do I check if an object is empty?

Use Object.keys(obj).length === 0. Checking if (obj) does not work because every object is truthy.

🤔 What does !! do in JavaScript?

It converts any value to its boolean equivalent: !!"text" is true, !!0 is false. It is the same as Boolean(value).


🏁 Summary

  • The 8 falsy values are false, 0, -0, 0n, "", null, undefined and NaN; everything else, including [] and {}, is truthy.
  • Truthiness checks treat 0 and "" as missing; compare explicitly when those are valid values.
  • == converts types before comparing; === does not. Use ===.
  • Objects and arrays are equal only if they are the same reference; use deep equality (toEqual, deepStrictEqual) for contents.
  • Normalise strings (trim, case) before comparing UI text, and convert numeric strings before comparing numbers.

Next, continue with Lesson 11: Optional Chaining and Nullish Coalescing.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Optional Chaining (?.) and Nullish Coalescing (??) with null and undefined

TypeError: Cannot read properties of undefined is probably the most common JavaScript error of all time. It happens when code reads a property of something that is not there, such as a field missing from an API response. Modern JavaScript has two operators made for this: optional chaining ?. reads a value safely, and nullish coalescing ?? supplies a default only when the value is really missing. In this lesson you will learn both, the difference between ?? and ||, and the logical assignment operators.

📖 What You’ll Learn: where null and undefined come from, the “Cannot read properties of undefined” error, optional chaining for properties, brackets and method calls, nullish coalescing and how it differs from ||, combining ?. and ??, logical assignment (??=, ||=, &&=), and when not to use them.


💥 The Error These Operators Prevent

null and undefined have no properties. Reading a property from either one throws a TypeError and stops the program:

📄 crash.js

const response = { user: { name: "Asha" } };   // no "address" field

console.log(response.user.name);
console.log(response.address);                 // missing property: undefined
console.log(response.address.city);            // reading a property OF undefined: crash

⌨️ Terminal

node crash.js

🖥️ Output

Asha
undefined
/home/you/js-course/crash.js:5
console.log(response.address.city);            // reading a property OF undefined: crash
                             ^

TypeError: Cannot read properties of undefined (reading 'city')
    at Object.<anonymous> (/home/you/js-course/crash.js:5:30)

Node.js v26.13.0

The message says exactly what happened: the code tried to read city from a value that is undefined. Missing values come from many places:

  • API fields that are optional or null.
  • Array elements that do not exist (items[10] on a 3-item list).
  • Function parameters the caller did not pass.
  • find() and similar methods when nothing matches (they return undefined).
  • DOM lookups such as document.querySelector() that find nothing (they return null).

🔗 Optional Chaining (?.)

Definition: the optional chaining operator ?. reads a property only if the value on its left is not null or undefined. If it is, the whole expression stops (“short-circuits”) and returns undefined instead of throwing.

📄 optional-chaining.js

const response = { user: { name: "Asha", address: null }, items: [] };

console.log(response.user?.name);              // "Asha"
console.log(response.user?.address?.city);     // address is null -> undefined
console.log(response.profile?.avatar?.url);    // profile missing -> undefined
console.log(response.items?.[0]?.price);       // brackets: no first item -> undefined

⌨️ Terminal

node optional-chaining.js

🖥️ Output

Asha
undefined
undefined
undefined

Optional chaining has three forms:

FormExampleMeaning
Propertyobj?.propRead prop if obj exists
Bracketobj?.[key], arr?.[0]Read a computed key or index if obj/arr exists
Callfn?.(), obj.method?.()Call the function only if it exists

📄 forms.js

const logger = { info: (msg) => console.log("INFO:", msg) };

logger.info?.("test started");      // method exists: called
logger.debug?.("details");          // method missing: skipped, no error

const field = "email";
const user = { email: "qa@sqatools.in" };
const guest = null;
console.log(user?.[field], guest?.[field]);

⌨️ Terminal

node forms.js

🖥️ Output

INFO: test started
qa@sqatools.in undefined

⚠️ Watch out: ?. only protects against null and undefined. It does not help if the value exists but is the wrong type: "text"?.toFixed() still throws because strings have no toFixed method.


🧩 Nullish Coalescing (??)

Definition: the nullish coalescing operator a ?? b returns a if it is not null or undefined, and b otherwise. “Nullish” means exactly those two values.

📄 nullish.js

const settings = { timeout: 0, retries: null, title: "" };

console.log(settings.timeout ?? 30000);   // 0 is a real value: kept
console.log(settings.retries ?? 2);       // null: default used
console.log(settings.headless ?? true);   // missing: default used
console.log(JSON.stringify(settings.title ?? "Untitled")); // "" is a real value: kept

⌨️ Terminal

node nullish.js

🖥️ Output

0
2
true
""

?? vs ||

Before ?? existed, people wrote defaults with ||. But || uses truthiness, so it also replaces 0, "", false and NaN, which are often valid values:

📄 or-vs-nullish.js

const config = { timeout: 0, headless: false, prefix: "" };

console.log("||:", config.timeout || 30000, config.headless || true, JSON.stringify(config.prefix || "test-"));
console.log("??:", config.timeout ?? 30000, config.headless ?? true, JSON.stringify(config.prefix ?? "test-"));

⌨️ Terminal

node or-vs-nullish.js

🖥️ Output

||: 30000 true "test-"
??: 0 false ""
Left valuevalue || "default"value ?? "default"
undefined“default”“default”
null“default”“default”
0“default”0
""“default”“”
false“default”false
NaN“default”NaN

💡 Tip: Use ?? for defaults of settings and data (numbers, booleans, strings that may be empty). Use || only when every falsy value should really be replaced, for example an empty search term that should fall back to “all”.


🤝 Combining ?. and ??

The two operators work best together: ?. reaches into nested data safely, and ?? replaces a missing result with a sensible default.

📄 combined.js

const orders = [
  { id: 1, customer: { name: "Asha", address: { city: "Pune" } }, discount: 0 },
  { id: 2, customer: { name: "Ravi" } },
  { id: 3 },
];

for (const order of orders) {
  const name = order.customer?.name ?? "Guest";
  const city = order.customer?.address?.city ?? "Unknown city";
  const discount = order.discount ?? "none";
  console.log(`#${order.id} ${name} - ${city} - discount: ${discount}`);
}

⌨️ Terminal

node combined.js

🖥️ Output

#1 Asha - Pune - discount: 0
#2 Ravi - Unknown city - discount: none
#3 Guest - Unknown city - discount: none

Mixing ?? directly with || or && is not allowed, because the intended order would be ambiguous. Add parentheses:

📄 mixing.js

const a = null, b = 0;
const result = a ?? b || 5;
console.log(result);

⌨️ Terminal

node mixing.js

🖥️ Output

/home/you/js-course/mixing.js:2
const result = a ?? b || 5;
                      ^^

SyntaxError: Unexpected token '||'

Node.js v26.13.0

📄 mixing-fixed.js

const a = null, b = 0;
console.log((a ?? b) || 5);
console.log(a ?? (b || 5));

⌨️ Terminal

node mixing-fixed.js

🖥️ Output

5
5

✍️ Logical Assignment: ??=, ||= and &&=

Logical assignment operators combine a check with an assignment (ES2021):

OperatorSame asAssigns when
a ??= ba ?? (a = b)a is null or undefined
a ||= ba || (a = b)a is falsy
a &&= ba && (a = b)a is truthy

📄 logical-assignment.js

const options = { retries: 0, baseURL: undefined, token: "abc123" };

options.retries ??= 2;           // 0 is kept
options.baseURL ??= "https://sqatools.in";
options.workers ??= 4;           // new property added
options.token &&= `Bearer ${options.token}`; // only changed if a token exists

console.log(options);

⌨️ Terminal

node logical-assignment.js

🖥️ Output

{
  retries: 0,
  baseURL: 'https://sqatools.in',
  token: 'Bearer abc123',
  workers: 4
}

A typical use is filling in defaults for a configuration object without overwriting values the user did provide.


🧪 Tester Scenario: Read an Unreliable API Response

Search APIs often omit empty fields. This function turns each raw result into a clean row for a report, without crashing on missing data:

📄 api-report.js

const apiResponse = {
  data: {
    results: [
      { sku: "P-1", title: "Pen", price: { amount: 10, currency: "INR" }, rating: 4.5 },
      { sku: "P-2", title: "Notebook", price: null, rating: 0 },
      { sku: "P-3", title: "Lamp" },
    ],
  },
};

const rows = (apiResponse.data?.results ?? []).map((item) => ({
  sku: item.sku,
  title: item.title ?? "(no title)",
  price: item.price?.amount ?? "N/A",
  currency: item.price?.currency ?? "-",
  rating: item.rating ?? "not rated",
}));

console.table(rows);

const firstOutOfStock = apiResponse.data?.results?.find((r) => r.stock === 0);
console.log("First out-of-stock SKU:", firstOutOfStock?.sku ?? "none");

⌨️ Terminal

node api-report.js

🖥️ Output

┌─────────┬───────┬────────────┬───────┬──────────┬─────────────┐
│ (index) │ sku   │ title      │ price │ currency │ rating      │
├─────────┼───────┼────────────┼───────┼──────────┼─────────────┤
│ 0       │ 'P-1' │ 'Pen'      │ 10    │ 'INR'    │ 4.5         │
│ 1       │ 'P-2' │ 'Notebook' │ 'N/A' │ '-'      │ 0           │
│ 2       │ 'P-3' │ 'Lamp'     │ 'N/A' │ '-'      │ 'not rated' │
└─────────┴───────┴────────────┴───────┴──────────┴─────────────┘
First out-of-stock SKU: none
  • apiResponse.data?.results ?? [] guarantees an array, so map always works.
  • The rating 0 is kept because ?? only replaces null/undefined. With || it would wrongly show “not rated”.
  • find() returns undefined when nothing matches, and ?.sku ?? "none" handles that.

⚠️ Watch out: In tests, do not use ?. and ?? to hide data that must be present. If the API contract says price is required, assert that it exists (expect(item.price).toBeDefined()) so the test fails and reports the defect, instead of printing “N/A”.


📝 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. Safely print the city from const user = { profile: null }, printing Unknown when it is missing.

Show answer

📄 practice1.js

const user = { profile: null };
console.log(user.profile?.address?.city ?? "Unknown");

🖥️ Output

Unknown

Q2. Predict the output of each line, then run it.

console.log(0 || 10);
console.log(0 ?? 10);
console.log("" || "x");
console.log("" ?? "x");
console.log(null ?? false ?? "z");
Show answer

📄 practice2.js

console.log(0 || 10);
console.log(0 ?? 10);
console.log("" || "x");
console.log("" ?? "x");
console.log(null ?? false ?? "z");

🖥️ Output

10
0
x

false

In the last line, null ?? false gives false, which is not nullish, so the chain stops there.

Q3. Write getRetries(config) that returns config.retries if it was set (including 0), otherwise 2. It must also work when config itself is undefined.

Show answer

📄 practice3.js

function getRetries(config) {
  return config?.retries ?? 2;
}

console.log(getRetries({ retries: 0 }));
console.log(getRetries({ retries: 5 }));
console.log(getRetries({}));
console.log(getRetries(undefined));

🖥️ Output

0
5
2
2

Q4. Call hooks.onFinish() only if it exists, for both hooks = { onFinish: () => console.log("done") } and hooks = {}.

Show answer

📄 practice4.js

const withHook = { onFinish: () => console.log("done") };
const withoutHook = {};

withHook.onFinish?.();
withoutHook.onFinish?.();
console.log("no error");

🖥️ Output

done
no error

Q5. Fill in defaults with ??=: browser should default to "chromium" and headless to true, but an explicit headless: false must be kept.

Show answer

📄 practice5.js

const run = { headless: false };
run.browser ??= "chromium";
run.headless ??= true;
console.log(run);

🖥️ Output

{ headless: false, browser: 'chromium' }

Q6. From const tests = [{ name: "login", tags: ["smoke"] }, { name: "search" }], print each test with its first tag, or untagged.

Show answer

📄 practice6.js

const tests = [{ name: "login", tags: ["smoke"] }, { name: "search" }];
for (const t of tests) {
  console.log(`${t.name}: ${t.tags?.[0] ?? "untagged"}`);
}

🖥️ Output

login: smoke
search: untagged

🧠 MCQ Quiz: Optional Chaining and Nullish Coalescing

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 does user?.address?.city return when user.address is null?
  2. What is 0 ?? 5?
  3. What is 0 || 5?
  4. Which values count as “nullish”?
  5. How do you call a method only if it exists?
  6. What happens with null ?? 0 || 1?
  7. What does items?.[0] do when items is undefined?
  8. After let a = 0; a ??= 10; what is a?
  9. After let b = 0; b ||= 10; what is b?
  10. What error does undefined.name throw?

💼 Interview Questions and Answers

Q1. What is the difference between ?? and ||?

a || b returns b whenever a is falsy (false, 0, "", NaN, null, undefined). a ?? b returns b only when a is null or undefined. Use ?? for defaults when 0, empty strings or false are valid values, such as a timeout of 0 or headless: false.

Q2. How does optional chaining short-circuit?

If the value before ?. is nullish, evaluation of the whole chain stops and the result is undefined; later property reads and function calls in that chain, including their arguments, are not evaluated.

📄 short-circuit.js

let calls = 0;
const count = () => ++calls;
const user = null;

console.log(user?.profile.getName(count()));
console.log("count() was called", calls, "times");

⌨️ Terminal

node short-circuit.js

🖥️ Output

undefined
count() was called 0 times

Q3. You see “TypeError: Cannot read properties of undefined (reading ‘id’)” in a test. How do you debug it?

  1. Read the stack trace to find the exact line and the expression ending in .id.
  2. Identify which object was undefined: log or inspect each part of the chain (for example response.body, response.body.items[0]).
  3. Find why it is missing: wrong API response, an empty list, a missing await (you received a Promise), or a find() that matched nothing.
  4. Fix the cause. If the value is legitimately optional, use ?. and ??; if it is required, add an assertion that reports a clear message.

Q4. When should you not use optional chaining?

When the value is required. Writing order?.id everywhere hides bugs: the code keeps running with undefined and fails later, far from the cause, or a test passes while checking nothing. Use ?. for data that is genuinely optional, and let required data fail fast (or validate it at the boundary, for example when parsing an API response).

Q5. What do ??=, ||= and &&= do?

They are logical assignment operators (ES2021). a ??= b assigns b only if a is nullish; a ||= b only if a is falsy; a &&= b only if a is truthy. They short-circuit, so the assignment (and evaluating b) does not happen when the condition is not met. A common use is applying default options.


❓ Frequently Asked Questions

🤔 Which JavaScript versions support ?. and ???

Both were added in ES2020 and work in all current browsers and every supported Node.js version. Logical assignment (??=, ||=, &&=) arrived in ES2021.

🤔 Can I use optional chaining on the left side of an assignment?

No. user?.name = "Asha" is a SyntaxError. Check first, for example if (user) user.name = "Asha";.

🤔 Is optional chaining slower?

The cost is negligible. Choose it for clarity and safety where values are optional.

🤔 What is the difference between null and undefined here?

None: ?., ?? and ??= treat both as “missing”. Their difference matters elsewhere, as explained in the Data Types lesson.


🏁 Summary

  • Reading a property of null or undefined throws “Cannot read properties of undefined”.
  • ?. reads properties, indexes (?.[ ]) and calls (?.()) safely, returning undefined when the left side is nullish.
  • ?? supplies a default only for null/undefined, keeping valid 0, "" and false; || replaces every falsy value.
  • ??=, ||= and &&= assign conditionally; mixing ?? with || needs parentheses.
  • Use these operators for optional data, and assertions for required data.

Next, continue with Lesson 12: Operators. This completes Module 2. Module 3 continues with operators and control flow.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Numbers, Math Object and BigInt: Rounding, Random and Precision

Prices, quantities, timeouts, percentages and IDs are all numbers, and tests compare them all the time. JavaScript numbers have a few surprises, such as 0.1 + 0.2 not being exactly 0.3, and IDs that silently lose digits. In this lesson you will learn how numbers are stored, how to round and format them correctly, how to use the Math object and random numbers for test data, and when to switch to BigInt.

📖 What You’ll Learn: the number type and floating-point precision, comparing decimals safely, integer limits, Infinity and NaN, number methods (toFixed, toPrecision, toLocaleString, Intl.NumberFormat), Number static methods, the Math object, random integers, money calculations in cents, and BigInt.


🔢 The Number Type

Definition: JavaScript has one number type for integers and decimals. Every number is stored as a 64-bit floating-point value (the IEEE 754 “double” format), the same as double in Java or float in Python.

📄 numbers.js

const quantity = 3;            // integer
const price = 19.99;           // decimal
const big = 1_000_000;         // _ separators make long numbers readable
const tiny = 2.5e-3;           // scientific notation: 0.0025
const hex = 0xff, binary = 0b1010, octal = 0o17;

console.log(quantity, price, big, tiny);
console.log(hex, binary, octal);
console.log(typeof quantity, typeof price);

⌨️ Terminal

node numbers.js

🖥️ Output

3 19.99 1000000 0.0025
255 10 15
number number

Numeric separators (1_000_000) are only for readability in source code; the value is the same as 1000000.


🎯 Floating-Point Precision: Why 0.1 + 0.2 !== 0.3

Many decimal fractions, such as 0.1, cannot be stored exactly in binary, just as 1/3 cannot be written exactly in decimal. Tiny rounding errors appear in the results:

📄 precision.js

console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
console.log(19.99 * 3);
console.log(1.005 * 100);

⌨️ Terminal

node precision.js

🖥️ Output

0.30000000000000004
false
59.97
100.49999999999999

This is not a JavaScript bug; every language that uses IEEE 754 doubles behaves the same way. There are three safe ways to deal with it:

1. Compare with a tolerance

📄 tolerance.js

function almostEqual(a, b, tolerance = 1e-9) {
  return Math.abs(a - b) < tolerance;
}

console.log(almostEqual(0.1 + 0.2, 0.3));
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);

⌨️ Terminal

node tolerance.js

🖥️ Output

true
true

2. Round only for display

📄 display.js

const total = 19.99 * 3;
console.log(total.toFixed(2));          // "59.97" (a string)
console.log(Number(total.toFixed(2)));  // 59.97 (a number)

⌨️ Terminal

node display.js

🖥️ Output

59.97
59.97

3. Calculate money in whole cents (or paise)

📄 cents.js

const pricesInCents = [1999, 1999, 1999];
const totalCents = pricesInCents.reduce((sum, c) => sum + c, 0);
console.log(totalCents, "cents =", (totalCents / 100).toFixed(2));

⌨️ Terminal

node cents.js

🖥️ Output

5997 cents = 59.97

💡 Tip: Test frameworks have tolerance assertions built in. In Playwright and Jest use expect(total).toBeCloseTo(59.97, 2) instead of toBe for decimal results.


📏 Integer Limits, Infinity and NaN

A double can represent every integer exactly only up to 253 − 1. Beyond that, integers lose precision silently, which matters for large database IDs and timestamps in nanoseconds.

📄 limits.js

console.log(Number.MAX_SAFE_INTEGER);
console.log(Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2); // precision lost!
console.log(Number.isSafeInteger(9007199254740993));
console.log(JSON.parse('{"orderId": 9007199254740993}').orderId); // last digit changed

⌨️ Terminal

node limits.js

🖥️ Output

9007199254740991
true
false
9007199254740992

📄 special.js

console.log(1 / 0, -1 / 0);          // Infinity, -Infinity
console.log(0 / 0, Math.sqrt(-1));   // NaN
console.log(Number.MAX_VALUE * 2);   // overflow -> Infinity
console.log(Number.isFinite(1 / 0), Number.isFinite(42));

⌨️ Terminal

node special.js

🖥️ Output

Infinity -Infinity
NaN NaN
Infinity
false true

⚠️ Watch out: Dividing by zero does not throw an error in JavaScript; it returns Infinity or NaN. Validate divisors (for example, an average over zero test runs) before calculating.


🛠️ Number Methods and Formatting

📄 methods.js

const n = 1234.5678;

console.log(n.toFixed(2));        // fixed decimals (string)
console.log(n.toFixed(0));        // rounds to a whole number
console.log(n.toPrecision(3));    // 3 significant digits
console.log((0.000123).toExponential(1));

console.log(Number.isInteger(5.0), Number.isInteger(5.5));
console.log(Number.parseFloat("2.5kg"), Number.parseInt("42", 10));

⌨️ Terminal

node methods.js

🖥️ Output

1234.57
1235
1.23e+3
1.2e-4
true false
2.5 42

toLocaleString() and Intl.NumberFormat format numbers the way people in a region expect, with grouping, currency symbols and percentages:

📄 format.js

const amount = 1234567.891;

console.log(amount.toLocaleString("en-US"));
console.log(amount.toLocaleString("en-IN"));   // Indian lakh/crore grouping
console.log(amount.toLocaleString("de-DE"));

const inr = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const pct = new Intl.NumberFormat("en-US", { style: "percent", maximumFractionDigits: 1 });
console.log(inr.format(1299.5), usd.format(1299.5), pct.format(0.875));

⌨️ Terminal

node format.js

🖥️ Output

1,234,567.891
12,34,567.891
1.234.567,891
₹1,299.50 $1,299.50 87.5%

💡 Tip: When a test checks a formatted price on a page, build the expected string with the same Intl.NumberFormat settings instead of hard-coding it. The test then stays correct for any amount.


🧮 The Math Object

Definition: Math is a built-in object with mathematical constants and functions. You never create it with new; call its methods directly.

📄 math.js

console.log(Math.round(4.5), Math.round(4.4), Math.round(-4.5));
console.log(Math.floor(4.9), Math.ceil(4.1), Math.trunc(-4.9));
console.log(Math.abs(-7), Math.sign(-7));
console.log(Math.max(3, 9, 4), Math.min(...[8, 2, 6]));
console.log(Math.pow(2, 10), 2 ** 10, Math.sqrt(144), Math.cbrt(27));
console.log(Math.PI.toFixed(4), Math.hypot(3, 4));

⌨️ Terminal

node math.js

🖥️ Output

5 4 -4
4 5 -4
7 -1
9 2
1024 1024 12 3
3.1416 5
MethodWhat it doesExample
Math.round(x)Nearest integer (.5 rounds up toward +∞)Math.round(2.5) → 3
Math.floor(x)Rounds downMath.floor(2.9) → 2
Math.ceil(x)Rounds upMath.ceil(2.1) → 3
Math.trunc(x)Removes the decimal partMath.trunc(-2.9) → -2
Math.max / minLargest / smallest argumentUse spread for arrays: Math.max(...arr)
Math.abs(x)Absolute valueMath.abs(-3) → 3
Math.random()Random number from 0 (inclusive) to 1 (exclusive)See below

Rounding to N decimal places

A common helper multiplies, rounds and divides. Because of floating-point errors, add Number.EPSILON for values like 1.005:

📄 round.js

const roundTo = (value, places) => {
  const factor = 10 ** places;
  return Math.round((value + Number.EPSILON) * factor) / factor;
};

console.log(Math.round(1.005 * 100) / 100); // naive version: 1 (wrong)
console.log(roundTo(1.005, 2));             // 1.01
console.log(roundTo(59.969999, 2));

⌨️ Terminal

node round.js

🖥️ Output

1
1.01
59.97

🎲 Random Numbers for Test Data

Math.random() returns a decimal from 0 up to (but not including) 1. Scale it to get random integers in a range:

📄 random.js

// Random integer from min to max, both included
function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

const rolls = Array.from({ length: 10 }, () => randomInt(1, 6));
console.log("10 dice rolls:", rolls.join(" "));
console.log("all between 1 and 6?", rolls.every((r) => r >= 1 && r <= 6));

const items = ["pen", "book", "lamp"];
const pick = items[randomInt(0, items.length - 1)];
console.log("random item is valid?", items.includes(pick));

const email = `qa+${Date.now()}${randomInt(100, 999)}@sqatools.in`;
console.log("unique email format ok?", /^qa\+\d+@sqatools\.in$/.test(email));

⌨️ Terminal

node random.js

🖥️ Output

10 dice rolls: 2 5 6 4 2 2 3 5 2 1
all between 1 and 6? true
random item is valid? true
unique email format ok? true

The rolls change every run; the checks stay true. Unique emails built from Date.now() and a random part are a common way to avoid “user already exists” errors when tests create accounts.

⚠️ Watch out: Math.random() is not secure. For tokens or passwords use crypto.randomUUID() or crypto.getRandomValues(). And when a test fails with random data, log the data you used, or the failure cannot be reproduced.


🐘 BigInt: Integers of Any Size

Definition: bigint is a separate primitive type for whole numbers of any size. Create one with an n suffix or with BigInt().

📄 bigint.js

const id = 9007199254740993n;
const next = id + 1n;
console.log(id, next);
console.log(typeof id);
console.log(BigInt("123456789012345678901234567890") * 2n);
console.log(7n / 2n);                 // integer division: the decimal part is dropped
console.log(10n > 9, 10n == 10, 10n === 10);

⌨️ Terminal

node bigint.js

🖥️ Output

9007199254740993n 9007199254740994n
bigint
246913578024691357802469135780n
3n
true true false

You cannot mix BigInt and regular numbers in arithmetic; convert one of them explicitly:

📄 mix.js

const big = 10n;
console.log(big + 5);

⌨️ Terminal

node mix.js

🖥️ Output

/home/you/js-course/mix.js:2
console.log(big + 5);
                ^

TypeError: Cannot mix BigInt and other types, use explicit conversions
    at Object.<anonymous> (/home/you/js-course/mix.js:2:17)

Node.js v26.13.0

📄 mix-fixed.js

const big = 10n;
console.log(big + BigInt(5));
console.log(Number(big) + 5);

⌨️ Terminal

node mix-fixed.js

🖥️ Output

15n
15
  • BigInt has no decimals and does not work with Math methods.
  • JSON.stringify throws on BigInt values. Send large IDs as strings in APIs.
  • Use BigInt for large IDs, counters and cryptography; use regular numbers for everything else.

📝 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. A cart has items priced 0.1 and 0.2. Write a check that confirms the total is 0.3 without failing because of floating-point errors.

Show answer

📄 practice1.js

const total = 0.1 + 0.2;
const ok = Math.abs(total - 0.3) < 1e-9;
console.log(total, ok ? "total is 0.3" : "total is wrong");

🖥️ Output

0.30000000000000004 total is 0.3

Q2. Calculate 18% GST on ₹1,499 and print the tax and the final price, both rounded to two decimal places.

Show answer

📄 practice2.js

const price = 1499;
const tax = Math.round(price * 0.18 * 100) / 100;
const finalPrice = Math.round((price + tax) * 100) / 100;
console.log(`Tax: ${tax.toFixed(2)}, Final: ${finalPrice.toFixed(2)}`);

🖥️ Output

Tax: 269.82, Final: 1768.82

Q3. Find the highest, lowest and average response time in [120, 340, 95, 210, 180] milliseconds. Print the average with no decimals.

Show answer

📄 practice3.js

const times = [120, 340, 95, 210, 180];
const max = Math.max(...times);
const min = Math.min(...times);
const avg = times.reduce((s, t) => s + t, 0) / times.length;
console.log(`max ${max} ms, min ${min} ms, avg ${Math.round(avg)} ms`);

🖥️ Output

max 340 ms, min 95 ms, avg 189 ms

Q4. Write randomPhone() that returns a 10-digit string starting with 9, and check that 5 generated numbers all match /^9\d{9}$/.

Show answer

📄 practice4.js

function randomPhone() {
  let digits = "9";
  for (let i = 0; i < 9; i++) {
    digits += Math.floor(Math.random() * 10);
  }
  return digits;
}

const phones = Array.from({ length: 5 }, randomPhone);
console.log(phones.every((p) => /^9\d{9}$/.test(p)));

🖥️ Output

true

Building the number digit by digit as a string keeps leading digits intact and avoids precision problems.

Q5. Format 2500000 as Indian rupees and as US dollars.

Show answer

📄 practice5.js

const amount = 2500000;
console.log(new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(amount));
console.log(new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amount));

🖥️ Output

₹25,00,000.00
$2,500,000.00

Q6. An API returns the order ID "9007199254740995" as a string. Add 2 to it without losing precision and print the result as a string.

Show answer

📄 practice6.js

const id = "9007199254740995";
console.log(Number(id) + 2);              // precision lost
console.log((BigInt(id) + 2n).toString()); // exact

🖥️ Output

9007199254740998
9007199254740997

🧠 MCQ Quiz: Numbers, Math and BigInt

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 does 0.1 + 0.2 === 0.3 return?
  2. How many number types does JavaScript have for integers and decimals (excluding BigInt)?
  3. What does (1.005).toFixed(2) return?
  4. What is Math.floor(-2.5)?
  5. Which expression returns a random integer from 1 to 6 inclusive?
  6. What is 1 / 0 in JavaScript?
  7. What is Number.MAX_SAFE_INTEGER?
  8. What happens with 10n + 5?
  9. How should a test compare a calculated decimal total?
  10. What does Math.max(...[4, 11, 7]) return?

💼 Interview Questions and Answers

Q1. Why is 0.1 + 0.2 not equal to 0.3, and how do you handle it?

Numbers are IEEE 754 binary doubles, and 0.1 and 0.2 have no exact binary representation, so their sum is 0.30000000000000004. Handle it by comparing with a tolerance (Math.abs(a - b) < 1e-9 or toBeCloseTo), rounding only when displaying (toFixed), or doing money arithmetic in integer cents, or with a decimal library for financial systems.

Q2. What is the difference between Math.round, Math.floor, Math.ceil and Math.trunc?

📄 rounding.js

for (const x of [2.5, -2.5, 2.4, -2.6]) {
  console.log(x, Math.round(x), Math.floor(x), Math.ceil(x), Math.trunc(x));
}

⌨️ Terminal

node rounding.js

🖥️ Output

2.5 3 2 3 2
-2.5 -2 -3 -2 -2
2.4 2 2 3 2
-2.6 -3 -3 -2 -2

round goes to the nearest integer, with .5 rounding toward positive infinity (so -2.5 becomes -2). floor always goes down, ceil always up, and trunc drops the fraction (toward zero).

Q3. A test intermittently fails when comparing order IDs from an API. The IDs are 19-digit numbers. What is wrong?

The IDs exceed Number.MAX_SAFE_INTEGER, so JSON.parse rounds them and different IDs can become equal or change their last digits. The API should send them as strings, and the test should compare them as strings or convert with BigInt. Check with Number.isSafeInteger().

Q4. How do you generate unique and reproducible test data?

For uniqueness, combine a timestamp, a random part or crypto.randomUUID(), for example qa+<timestamp>@domain. For reproducibility, log the generated values in the test report, or use a seeded random generator (for example Faker with faker.seed(123)) so a failing run can be repeated with the same data.

Q5. What is NaN, and how can it appear in a calculation?

NaN is a number value meaning “not a valid number”. It appears from failed conversions (Number("abc")), undefined maths (0 / 0, Math.sqrt(-1)), and arithmetic with undefined (a missing property). It spreads through every later calculation, so validate inputs with Number.isFinite() early.


❓ Frequently Asked Questions

🤔 How do I round a number to 2 decimal places in JavaScript?

For display, use num.toFixed(2) (returns a string). For a number, use Math.round((num + Number.EPSILON) * 100) / 100.

🤔 Does JavaScript have integers?

Regular numbers can hold integers exactly up to 253 − 1, but they are floating-point values. For larger integers use BigInt. Number.isInteger() tells you whether a number has no fractional part.

🤔 How do I generate a random number between two values?

Use Math.floor(Math.random() * (max - min + 1)) + min for an integer from min to max, both included.

🤔 When should I use BigInt?

Only for whole numbers larger than 9,007,199,254,740,991, such as large database IDs or nanosecond timestamps. It is slower and cannot be mixed with regular numbers.


🏁 Summary

  • All regular numbers are 64-bit floating-point values; 0.1 + 0.2 is not exactly 0.3.
  • Compare decimals with a tolerance, round only for display, and calculate money in cents.
  • Integers are exact only up to Number.MAX_SAFE_INTEGER; division by zero gives Infinity or NaN, not an error.
  • Math provides rounding, min/max, powers and random(); Intl.NumberFormat formats currencies and percentages.
  • BigInt (123n) handles integers of any size but cannot be mixed with regular numbers.

Next, continue with Lesson 10: Truthy, Falsy and Equality.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Console Methods and Debugging Basics (log, table, time, assert and more)

console.log() is the first tool every JavaScript developer and tester learns, but the console can do much more: print tables of test data, time how long a step takes, count calls, group related output and warn only when a check fails. In this lesson you will learn every console method worth knowing, how output goes to stdout and stderr, and how to pause a program with breakpoints and the debugger statement.

📖 What You’ll Learn: console.log, info, warn and error, format specifiers, console.table, console.group, console.time, console.count, console.assert, console.dir and console.trace, stdout versus stderr, the debugger statement, breakpoints in VS Code and node inspect.


📢 console.log, info, warn and error

Definition: the console object gives you methods to print messages. In Node.js they go to the terminal; in a browser they go to the DevTools Console.

📄 levels.js

console.log("Test suite started");
console.info("Base URL:", "https://sqatools.in");
console.warn("Retrying login, attempt", 2);
console.error("Login failed: status", 401);

⌨️ Terminal

node levels.js

🖥️ Output

Test suite started
Base URL: https://sqatools.in
Retrying login, attempt 2
Login failed: status 401
  • Pass several values separated by commas; the console prints them with a space between.
  • console.info is the same as console.log.
  • console.warn and console.error write to stderr (the error stream) instead of stdout. In the browser they appear in yellow and red and can be filtered by level.

💡 Tip: CI systems and shells can separate the two streams. node levels.js 2> errors.log sends only the warning and the error to errors.log, while the normal logs still appear in the terminal.


🧾 Printing Objects, Arrays and Formatted Text

The console formats objects and arrays so you can read them, which makes it ideal for checking API responses and test data.

📄 objects.js

const user = { id: 7, name: "Asha", roles: ["tester", "admin"], active: true };
const scores = [91, 78, 85];

console.log(user);
console.log("Scores:", scores);
console.log(`User ${user.name} has ${scores.length} scores`);

⌨️ Terminal

node objects.js

🖥️ Output

{ id: 7, name: 'Asha', roles: [ 'tester', 'admin' ], active: true }
Scores: [ 91, 78, 85 ]
User Asha has 3 scores

Format specifiers are placeholders in the first argument that are replaced by the following arguments:

SpecifierInserts
%sA string
%d or %iAn integer
%fA floating-point number
%o / %OAn object (detailed / plain)
%jJSON (Node.js only)
%cCSS styles (browser only; ignored in Node.js)

📄 format.js

console.log("%s passed %d of %d tests", "Asha", 18, 20);
console.log("Pass rate: %f%%", 90.5);
console.log("Payload: %j", { email: "qa@sqatools.in" });

⌨️ Terminal

node format.js

🖥️ Output

Asha passed 18 of 20 tests
Pass rate: 90.5%
Payload: {"email":"qa@sqatools.in"}

%% prints a literal percent sign. Template literals (`...${value}`) are usually easier to read, so use specifiers mainly when you see them in other people’s code.


📊 console.table: Show Data as a Table

console.table() prints an array of objects (or an object) as a table. It is perfect for test data and API results.

📄 table.js

const results = [
  { test: "login", status: "passed", ms: 812 },
  { test: "search", status: "failed", ms: 1530 },
  { test: "checkout", status: "passed", ms: 2104 },
];

console.table(results);
console.table(results, ["test", "status"]); // only these columns

⌨️ Terminal

node table.js

🖥️ Output

┌─────────┬────────────┬──────────┬──────┐
│ (index) │ test       │ status   │ ms   │
├─────────┼────────────┼──────────┼──────┤
│ 0       │ 'login'    │ 'passed' │ 812  │
│ 1       │ 'search'   │ 'failed' │ 1530 │
│ 2       │ 'checkout' │ 'passed' │ 2104 │
└─────────┴────────────┴──────────┴──────┘
┌─────────┬────────────┬──────────┐
│ (index) │ test       │ status   │
├─────────┼────────────┼──────────┤
│ 0       │ 'login'    │ 'passed' │
│ 1       │ 'search'   │ 'failed' │
│ 2       │ 'checkout' │ 'passed' │
└─────────┴────────────┴──────────┘

The (index) column shows the array position. The second argument limits which columns are printed.


🗂️ console.group: Indent Related Output

console.group(label) starts an indented section and console.groupEnd() closes it. Groups can be nested.

📄 group.js

console.group("Checkout flow");
console.log("Add item to cart");
console.group("Payment");
console.log("Enter card details");
console.log("Confirm order");
console.groupEnd();
console.log("Show confirmation page");
console.groupEnd();
console.log("Flow finished");

⌨️ Terminal

node group.js

🖥️ Output

Checkout flow
  Add item to cart
  Payment
    Enter card details
    Confirm order
  Show confirmation page
Flow finished

In the browser, console.groupCollapsed() creates a group that starts closed, which keeps long logs tidy.


⏱️ console.time and console.count

console.time(label) starts a timer and console.timeEnd(label) stops it and prints the elapsed time. console.timeLog(label) prints the time so far without stopping.

📄 timer.js

console.time("build report");

let total = 0;
for (let i = 0; i < 1_000_000; i++) {
  total += i;
}
console.timeLog("build report", "loop done");

const report = JSON.stringify({ total });
console.timeEnd("build report");
console.log(report);

⌨️ Terminal

node timer.js

🖥️ Output

build report: 2.44ms loop done
build report: 4.052ms
{"total":499999500000}

Your times will differ; they depend on your computer. Use labels so you can run several timers at once.

console.count(label) prints how many times it has been called with that label. console.countReset(label) sets it back to zero.

📄 count.js

function retry(action) {
  console.count(`retry ${action}`);
}

retry("login");
retry("login");
retry("upload");
retry("login");
console.countReset("retry login");
retry("login");

⌨️ Terminal

node count.js

🖥️ Output

retry login: 1
retry login: 2
retry upload: 1
retry login: 3
retry login: 1

✅ console.assert: Log Only When a Check Fails

console.assert(condition, ...message) prints Assertion failed with your message only when the condition is false. Unlike node:assert, it does not stop the program.

📄 assert.js

const statusCode = 500;
const items = ["pen", "book"];

console.assert(items.length === 2, "Expected 2 items");
console.assert(statusCode === 200, "Expected status 200 but got", statusCode);
console.log("The program keeps running after a failed console.assert");

⌨️ Terminal

node assert.js

🖥️ Output

Assertion failed: Expected status 200 but got 500
The program keeps running after a failed console.assert

⚠️ Watch out: console.assert is for quick debugging only. A test must fail when a check fails, so in tests use node:assert, expect() from Jest or Vitest, or Playwright’s expect(), which throw an error and mark the test as failed.


🔬 console.dir and console.trace

console.log stops showing nested objects after 2 levels and prints [Object] instead. console.dir(obj, { depth: null }) prints every level.

📄 dir.js

const response = {
  status: 200,
  body: { user: { profile: { address: { city: "Pune" } } } },
};

console.log(response);
console.dir(response, { depth: null });

⌨️ Terminal

node dir.js

🖥️ Output

{ status: 200, body: { user: { profile: [Object] } } }
{
  status: 200,
  body: {
    user: { profile: { address: { city: 'Pune' } } }
  }
}

console.trace() prints a message plus the call stack: the chain of function calls that led to this line. It answers “who called this function?”.

📄 trace.js

function saveOrder() {
  console.trace("saveOrder was called");
}
function checkout() {
  saveOrder();
}
checkout();

⌨️ Terminal

node trace.js

🖥️ Output

Trace: saveOrder was called
    at saveOrder (/home/you/js-course/trace.js:2:11)
    at checkout (/home/you/js-course/trace.js:5:3)
    at Object.<anonymous> (/home/you/js-course/trace.js:7:1)

Read the stack from the top: saveOrder was called by checkout (line 5), which was called from the top of the file (line 7).


🐞 Debugging Basics: Breakpoints and the debugger Statement

Logging is quick, but a debugger lets you pause a running program, inspect every variable and step through it line by line.

Breakpoints in VS Code

  1. Open the file and click in the gutter left of a line number. A red dot (the breakpoint) appears.
  2. Press F5 and choose Node.js. The program stops at the breakpoint, before running that line.
  3. Hover over a variable, or look in the Variables panel, to see its value.
  4. Use the toolbar: Continue (F5), Step Over (F10), Step Into (F11) and Step Out (Shift+F11).

The debugger statement

Writing debugger; in your code acts like a breakpoint, but only when a debugger is attached (VS Code with F5, Chrome DevTools open, or node inspect). Without a debugger it does nothing, which the next run proves:

📄 debug.js

function calculateTotal(prices) {
  let total = 0;
  for (const price of prices) {
    debugger; // pauses here only when a debugger is attached
    total += price;
  }
  return total;
}

console.log("Total:", calculateTotal([10, 20, 30]));

⌨️ Terminal

node debug.js

🖥️ Output

Total: 60

To use the built-in terminal debugger, run node inspect debug.js. Type cont to run to the next debugger statement, repl to inspect variables, and .exit to quit. Chrome can also attach to node --inspect-brk debug.js from chrome://inspect.

💡 Tip: Remove debugger; statements and noisy console.log calls before you commit code. ESLint’s no-debugger and no-console rules can remind you.


📋 Console Method Cheat Sheet

MethodUse it to
console.log / infoPrint general messages and values
console.warn / errorPrint warnings and errors (to stderr)
console.tableShow arrays of objects as a table
console.group / groupEndIndent related messages
console.time / timeLog / timeEndMeasure how long code takes
console.count / countResetCount how often a line runs
console.assertPrint a message only when a condition is false
console.dirPrint deep objects with { depth: null }
console.tracePrint the call stack
console.clearClear the console (browser and terminal)

📝 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 Order 1042 shipped to Pune twice: once with a template literal and once with format specifiers.

Show answer

📄 practice1.js

const id = 1042;
const city = "Pune";
console.log(`Order ${id} shipped to ${city}`);
console.log("Order %d shipped to %s", id, city);

🖥️ Output

Order 1042 shipped to Pune
Order 1042 shipped to Pune

Q2. Show this data as a table with only the name and price columns.

const products = [
  { name: "Pen", price: 10, stock: 120 },
  { name: "Notebook", price: 45, stock: 30 },
];
Show answer

📄 practice2.js

const products = [
  { name: "Pen", price: 10, stock: 120 },
  { name: "Notebook", price: 45, stock: 30 },
];
console.table(products, ["name", "price"]);

🖥️ Output

┌─────────┬────────────┬───────┐
│ (index) │ name       │ price │
├─────────┼────────────┼───────┤
│ 0       │ 'Pen'      │ 10    │
│ 1       │ 'Notebook' │ 45    │
└─────────┴────────────┴───────┘

Q3. Measure how long it takes to build an array of 100,000 numbers, using a timer labelled fill.

Show answer

📄 practice3.js

console.time("fill");
const numbers = [];
for (let i = 0; i < 100_000; i++) {
  numbers.push(i);
}
console.timeEnd("fill");
console.log("Length:", numbers.length);

🖥️ Output

fill: 3.88ms
Length: 100000

The time printed will be different on your computer.

Q4. Use console.assert to print a message only if a password is shorter than 8 characters. Test it with "secret".

Show answer

📄 practice4.js

const password = "secret";
console.assert(password.length >= 8, "Password too short:", password.length, "characters");

🖥️ Output

Assertion failed: Password too short: 6 characters

The condition describes what should be true. Because 6 >= 8 is false, the message is printed.

Q5. Count how many times clickButton() is called with each button name, for the calls "save", "cancel", "save".

Show answer

📄 practice5.js

function clickButton(name) {
  console.count(name);
}
clickButton("save");
clickButton("cancel");
clickButton("save");

🖥️ Output

save: 1
cancel: 1
save: 2

Q6. console.log(config) prints [Object] for a nested value. Print the whole object instead.

const config = { env: { qa: { db: { host: "qa-db", port: 5432 } } } };
Show answer

📄 practice6.js

const config = { env: { qa: { db: { host: "qa-db", port: 5432 } } } };
console.dir(config, { depth: null });

🖥️ Output

{
  env: { qa: { db: { host: 'qa-db', port: 5432 } } }
}

You can also use console.log(JSON.stringify(config, null, 2)) to print it as indented JSON.


🧠 MCQ Quiz: Console Methods and Debugging Basics

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. Where does console.error() write its output in Node.js?
  2. Which method prints an array of objects as rows and columns?
  3. What does console.log("%d items", 3) print?
  4. What happens when console.assert(false, "Oops") runs?
  5. Which pair measures elapsed time?
  6. Why might console.log(obj) print [Object]?
  7. What does console.trace() show?
  8. When does a debugger; statement pause the program?
  9. In VS Code, which key steps over the current line while debugging?
  10. Why should tests use node:assert or expect() instead of console.assert?

💼 Interview Questions and Answers

Q1. What is the difference between console.log and console.error, and why does it matter in CI?

console.log writes to stdout and console.error (and console.warn) write to stderr. CI systems, Docker and shells can capture or redirect each stream separately, and some tools treat anything on stderr as a warning. Logging real errors with console.error makes failures easier to find and filter, while keeping normal progress logs on stdout.

Q2. How would you find which test step is slow in a Node.js script?

Wrap each step with console.time("step") / console.timeEnd("step"), or record performance.now() before and after for precise numbers you can assert on. For deeper analysis, run with node --cpu-prof or attach Chrome DevTools via node --inspect and record a performance profile. In Playwright, the trace viewer shows the duration of every action.

Q3. Explain how you would debug a failing function without adding console.log everywhere.

  1. Set a breakpoint on the first line of the function in VS Code (or add debugger;).
  2. Start with F5 (Node.js) so the debugger is attached.
  3. When it pauses, inspect the arguments in the Variables panel and add watch expressions.
  4. Step over (F10) line by line until a value differs from what you expect; step into (F11) helper calls when needed.
  5. Use the Call Stack panel to see who called the function with the bad input, then fix the root cause.

Q4. What is a call stack, and how does console.trace help?

The call stack is the list of functions that are currently running, with the most recent call on top. When an error occurs, its stack trace shows the same list. console.trace() prints the stack on demand, which shows the path that led to a line, for example which test or page-object method called a helper with the wrong data.

📄 who-called.js

function login(user) {
  if (!user) console.trace("login called without a user");
}
function runTest() {
  login(undefined);
}
runTest();

⌨️ Terminal

node who-called.js

🖥️ Output

Trace: login called without a user
    at login (/home/you/js-course/who-called.js:2:22)
    at runTest (/home/you/js-course/who-called.js:5:3)
    at Object.<anonymous> (/home/you/js-course/who-called.js:7:1)

❓ Frequently Asked Questions

🤔 Does console.log slow down my program?

A few logs do not matter. Logging inside loops that run thousands of times, or printing huge objects, can slow programs noticeably, so remove debug logs when you are done.

🤔 Why do I not see console.log output from my web page in the terminal?

Code in a web page runs in the browser, so its logs appear in the browser DevTools Console (F12). Only code run by Node.js prints to the terminal. Playwright can forward page logs with page.on("console", ...).

🤔 How do I clear the console?

Call console.clear(), press Ctrl+L in the browser console, or run clear (macOS/Linux) or cls (Windows) in the terminal.

🤔 Should I leave console.log statements in my code?

Remove temporary debugging logs before committing. Keep only intentional logging, and in larger projects use a logging library that supports levels such as debug, info and error.


🏁 Summary

  • console.log/info write to stdout; console.warn/error write to stderr.
  • console.table, group, time, count, dir and trace make output easier to read and analyse.
  • console.assert logs failed checks but does not stop the program; tests need throwing assertions.
  • Breakpoints and the debugger statement pause execution when a debugger is attached (VS Code F5, Chrome DevTools, node inspect).
  • Read stack traces from the top to find where an error happened and who called that code.

Next, continue with Lesson 6: Variables: var, let, const. Module 2 starts with variables, where you will use the console to inspect every value you create.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Syntax: Statements, Semicolons, Comments and Strict Mode

Every language has grammar rules, and JavaScript is no exception. Most “my code does not work” moments for beginners come from small syntax issues: a capital letter, a missing bracket, a line break after return. In this lesson you will learn the rules that every JavaScript file follows, how to write comments, when semicolons matter, and why every modern script runs in strict mode.

📖 What You’ll Learn: statements, expressions and blocks, case sensitivity, valid identifiers and reserved words, single-line, multi-line and JSDoc comments, semicolons and automatic semicolon insertion (ASI), strict mode and what it changes, and naming and style conventions.


🧱 Statements, Expressions and Blocks

Definition: a statement is one instruction that the program performs, such as declaring a variable or running an if. An expression is any piece of code that produces a value, such as 2 + 3 or price * 0.9. A block is a group of statements inside curly braces { }.

📄 statements.js

let price = 100;           // declaration statement
price = price * 0.9;       // expression statement (assignment)
console.log(price);        // expression statement (function call)

if (price < 95) {          // if statement with a block
  console.log("Discount applied");
  console.log("New price:", price);
}

⌨️ Terminal

node statements.js

🖥️ Output

90
Discount applied
New price: 90
  • price * 0.9 is an expression: it produces the value 90.
  • Statements run from top to bottom, one after another.
  • The two lines inside { } form one block. They run only when the condition is true.

💡 Tip: A quick test: if you can put the code on the right side of const x = ..., it is an expression. const x = 2 + 3 works; const x = if (...) does not, because if is a statement.


🔠 Case Sensitivity and Whitespace

JavaScript is case-sensitive: total, Total and TOTAL are three different names. Keywords are always lowercase (let, if, function).

📄 case.js

let total = 10;
let Total = 20;
console.log(total, Total);

⌨️ Terminal

node case.js

🖥️ Output

10 20

Spaces, tabs and line breaks between tokens are ignored, so the two statements below are identical. Use whitespace to make code readable, not to change its meaning.

📄 whitespace.js

const sum=1+2;
const   sum2   =   1   +   2  ;
console.log(sum === sum2);

⌨️ Terminal

node whitespace.js

🖥️ Output

true

🏷️ Identifiers and Reserved Words

Definition: an identifier is a name you give to a variable, function or class. The rules:

  • It may contain letters, digits, _ and $.
  • It must not start with a digit.
  • It must not be a reserved word such as let, class, return, if, new or function.
ValidInvalidWhy invalid
userNameuser-name- is the minus operator
_count, $price2ndUserStarts with a digit
item2classReserved word

Using a reserved word as a name is a syntax error, so the file does not run at all:

📄 reserved.js

let class = "QA";
console.log(class);

⌨️ Terminal

node reserved.js

🖥️ Output

/home/you/js-course/reserved.js:1
let class = "QA";
    ^^^^^

SyntaxError: Unexpected token 'class'

Node.js v26.13.0

💬 Comments: Single-Line, Multi-Line and JSDoc

Definition: a comment is text that JavaScript ignores. Use comments to explain why code does something, not to repeat what it does.

📄 comments.js

// Single-line comment: everything after // is ignored

/*
  Multi-line comment.
  Useful for longer notes or for temporarily disabling code.
*/

/**
 * JSDoc comment: documents a function for editors and tools.
 * @param {number} price - Original price
 * @param {number} percent - Discount from 0 to 100
 * @returns {number} Price after discount
 */
function applyDiscount(price, percent) {
  return price - (price * percent) / 100; // percent of the price
}

console.log(applyDiscount(250, 20));

⌨️ Terminal

node comments.js

🖥️ Output

200
  • // comments run to the end of the line, so they can follow code on the same line.
  • /* ... */ comments can span many lines but cannot be nested.
  • /** ... */ JSDoc comments are read by VS Code: hover over applyDiscount to see the description and parameter types.

💡 Tip: In VS Code, select lines and press Ctrl+/ to comment or uncomment them all at once.


🔚 Semicolons and Automatic Semicolon Insertion (ASI)

Statements end with a semicolon ;. If you leave it out, JavaScript usually inserts it for you at the line break. This is called Automatic Semicolon Insertion (ASI). It works most of the time, but two cases surprise everyone.

Trap 1: a line break after return

📄 asi-return.js

function getUser() {
  return
  { name: "Asha" };
}

console.log(getUser());

⌨️ Terminal

node asi-return.js

🖥️ Output

undefined

JavaScript inserts a semicolon right after return, so the function returns undefined and the object below it is never reached. Fix: put the opening brace on the same line: return {.

Trap 2: a line that starts with [ or (

📄 asi-array.js

const a = 1
const b = 2
[a, b].forEach((n) => console.log(n))

⌨️ Terminal

node asi-array.js

🖥️ Output

/home/you/js-course/asi-array.js:3
[a, b].forEach((n) => console.log(n))
    ^

ReferenceError: Cannot access 'b' before initialization
    at Object.<anonymous> (/home/you/js-course/asi-array.js:3:5)

Node.js v26.13.0

No semicolon is inserted after 2, because 2[a, b] could be valid code. JavaScript reads the last two lines as one statement, const b = 2[a, b].forEach(...), which uses b before it exists. Fix: end statements with semicolons.

⚠️ Watch out: Pick one style and let a tool enforce it. This course uses semicolons everywhere, which is the default in Prettier and avoids both traps.


🛡️ Strict Mode

Definition: strict mode is a safer version of JavaScript that turns silent mistakes into errors. Enable it by writing "use strict"; as the first statement of a file or a function.

Without strict mode (“sloppy mode”), assigning to a misspelled variable silently creates a new global variable:

📄 sloppy.js

let total = 0;

function addItem(price) {
  totl = total + price; // typo: "totl" instead of "total"
}

addItem(50);
console.log("total:", total);
console.log("accidental global:", globalThis.totl);

⌨️ Terminal

node sloppy.js

🖥️ Output

total: 0
accidental global: 50

The bug is hidden: total is still 0 and a stray global called totl appeared. With strict mode, the same typo stops the program at the exact line:

📄 strict.js

"use strict";

let total = 0;

function addItem(price) {
  totl = total + price; // typo: "totl" instead of "total"
}

addItem(50);

⌨️ Terminal

node strict.js

🖥️ Output

/home/you/js-course/strict.js:6
  totl = total + price; // typo: "totl" instead of "total"
       ^

ReferenceError: totl is not defined
    at addItem (/home/you/js-course/strict.js:6:8)
    at Object.<anonymous> (/home/you/js-course/strict.js:9:1)

Node.js v26.13.0
Strict modeWhat changes
Assigning to an undeclared variableThrows ReferenceError instead of creating a global
Duplicate parameter namesfunction f(a, a) {} is a SyntaxError
this in a plain function callIs undefined instead of the global object
Writing to a read-only propertyThrows TypeError instead of failing silently
Reserved words for the futurelet, static, implements, package and others cannot be used as names

📌 Note: You often get strict mode automatically. ES modules (files that use import/export, or .mjs files) and code inside a class are always strict. Playwright and most modern tools load your tests as modules, so strict rules apply there even without "use strict".

📄 module.mjs

// An .mjs file is an ES module, so strict mode is on automatically
count = 1;
console.log(count);

⌨️ Terminal

node module.mjs

🖥️ Output

file:///home/you/js-course/module.mjs:2
count = 1;
      ^

ReferenceError: count is not defined
    at file:///home/you/js-course/module.mjs:2:7

Node.js v26.13.0

✍️ Naming and Style Conventions

KindConventionExample
Variables and functionscamelCaseuserName, getTotalPrice()
ClassesPascalCaseLoginPage, ApiClient
Constants that never changeUPPER_SNAKE_CASEMAX_RETRIES, BASE_URL
BooleansStart with is/has/canisVisible, hasError
Fileskebab-caselogin-page.js, cart.test.js

Other widely used style rules: indent with 2 spaces, use double or single quotes consistently, put opening braces on the same line, and keep lines under about 100 characters. Prettier applies all of these for you when you save.

📄 naming.js

const MAX_RETRIES = 3;

class LoginPage {
  isLoggedIn = false;
}

function getRetryMessage(attempt) {
  return `Attempt ${attempt} of ${MAX_RETRIES}`;
}

const page = new LoginPage();
console.log(getRetryMessage(1), "| logged in:", page.isLoggedIn);

⌨️ Terminal

node naming.js

🖥️ Output

Attempt 1 of 3 | logged in: false

📝 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. Which of these identifiers are valid: firstName, 1stName, first_name, $total, first-name, new?

Show answer

Valid: firstName, first_name, $total. Invalid: 1stName (starts with a digit), first-name (contains -), new (reserved word).

Q2. Predict the output, then run the code to check.

function getStatus() {
  return
    "passed";
}
console.log(getStatus());
Show answer

📄 status.js

function getStatus() {
  return
    "passed";
}
console.log(getStatus());

🖥️ Output

undefined

ASI inserts a semicolon after return, so the function returns undefined. Put the value on the same line: return "passed";.

Q3. Add a JSDoc comment to this function describing its two parameters and return value.

function fullName(first, last) {
  return first + " " + last;
}
Show answer

📄 fullname.js

/**
 * Joins a first and last name.
 * @param {string} first - First name
 * @param {string} last - Last name
 * @returns {string} The full name
 */
function fullName(first, last) {
  return first + " " + last;
}

console.log(fullName("Asha", "Rao"));

🖥️ Output

Asha Rao

Q4. This code prints 0 instead of 15. Turn on strict mode to find the bug, then fix it.

let count = 0;
function add(n) {
  cuont = count + n;
}
add(15);
console.log(count);
Show answer

With "use strict"; at the top, Node.js throws ReferenceError: cuont is not defined and points to the typo. The fixed code:

📄 count.js

"use strict";

let count = 0;
function add(n) {
  count = count + n;
}
add(15);
console.log(count);

🖥️ Output

15

Q5. Rename these to follow conventions: a class checkout_page, a constant timeout that is always 30000, a boolean visible.

Show answer

CheckoutPage (PascalCase for classes), TIMEOUT_MS or DEFAULT_TIMEOUT (UPPER_SNAKE_CASE, and the unit in the name helps), isVisible (booleans start with is/has/can).

Q6. Fix the ASI bug so the program prints 1 and 2.

const a = 1
const b = 2
[a, b].forEach((n) => console.log(n))
Show answer

📄 fixed.js

const a = 1;
const b = 2;
[a, b].forEach((n) => console.log(n));

🖥️ Output

1
2

The semicolon after 2 ends the statement, so the array on the next line is a new statement.


🧠 MCQ Quiz: Syntax, Comments and Strict Mode

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 is an expression?
  2. Are userName and username the same variable?
  3. Which identifier is invalid?
  4. What does this return?
    function f() {
      return
      42;
    }
  5. How do you enable strict mode for a whole script file?
  6. In sloppy (non-strict) mode, what does assigning to an undeclared variable do?
  7. Which code always runs in strict mode automatically?
  8. Which comment style does VS Code show when you hover over a function?
  9. Why can const b = 2 followed by a line starting with [a, b] break?
  10. Which naming follows common JavaScript conventions?

💼 Interview Questions and Answers

Q1. What is the difference between a statement and an expression?

An expression produces a value (a + b, fn(), x > 5 ? "big" : "small") and can be used wherever a value is expected. A statement performs an action (if, for, return, a declaration). An expression followed by a semicolon is an “expression statement”. This matters for arrow functions: () => x + 1 returns the expression, but () => { x + 1 } is a block that returns undefined.

Q2. What is Automatic Semicolon Insertion, and when does it cause bugs?

ASI is the rule that inserts a semicolon at a line break when the next token cannot continue the statement, and always after return, break, continue and throw followed by a line break. Bugs appear when (1) a value is placed on the line after return, which returns undefined, and (2) a line starts with (, [ or a template literal, which joins it to the previous line. Using semicolons or a formatter avoids both.

📄 asi-fixed.js

function config() {
  return {
    retries: 2,
  };
}
console.log(config());

⌨️ Terminal

node asi-fixed.js

🖥️ Output

{ retries: 2 }

Q3. What is strict mode, and is it on in a Playwright test file?

Strict mode is an opt-in restricted variant of JavaScript, enabled with "use strict", that throws on silent errors (undeclared variables, writes to read-only properties, duplicate parameters) and makes this undefined in plain function calls. ES modules and class bodies are always strict. Playwright test files written as ES modules or in TypeScript are compiled as modules, so the strict rules apply.

Q4. Why does let class = 1 fail before any line of the file runs?

It is a syntax error, and syntax errors are found when the engine parses the whole file, before execution starts. Because class is a reserved word, the parser cannot build the program, so nothing runs, not even console.log calls above the bad line. Runtime errors such as ReferenceError, in contrast, happen only when that line executes.

Q5. How do you keep code style consistent across a test automation team?

Agree on conventions (naming, quotes, semicolons), then automate them: Prettier for formatting, ESLint for code-quality rules, an .editorconfig for indentation, format-on-save in VS Code, and a CI step (npx prettier --check . and npx eslint .) so style problems fail the build instead of code review.


❓ Frequently Asked Questions

🤔 Are semicolons required in JavaScript?

Not strictly, because of ASI, but leaving them out can cause the bugs shown in this lesson. Most teams use semicolons, or omit them consistently with a tool such as Prettier or ESLint that warns about the risky cases.

🤔 Should I write “use strict” in every file?

Only in classic scripts and CommonJS files. ES modules, classes and most modern tooling are strict automatically, and adding the directive there does no harm.

🤔 How many types of comments are there in JavaScript?

Two: single-line // and multi-line /* */. JSDoc comments (/** */) are multi-line comments with a special format that editors understand.

🤔 Is JavaScript whitespace-sensitive like Python?

No. Indentation does not change the meaning of JavaScript code. Line breaks matter only for ASI, which is why return followed by a line break returns undefined.


🏁 Summary

  • Statements perform actions; expressions produce values; blocks { } group statements.
  • JavaScript is case-sensitive, and identifiers cannot start with a digit or be reserved words.
  • Use // and /* */ comments to explain why, and JSDoc to document functions.
  • ASI inserts semicolons at line breaks, but never put a value on the line after return and never start a line with [ or ( without a semicolon before it.
  • Strict mode turns silent mistakes into errors; ES modules and classes are always strict.

Next, continue with Lesson 5: Console Methods and Debugging Basics.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

How to Run JavaScript: Browser Console, Node.js REPL, Files and Web Pages

Before you learn the language itself, you need a quick, reliable way to run code and see the result. JavaScript can run in five places: the browser console, the Node.js REPL, a .js file, a one-line terminal command and a web page. In this lesson you will use all five, learn when to pick each one, and fix the errors beginners hit most often, such as document is not defined.

📖 What You’ll Learn: the browser DevTools console, the Node.js REPL and its commands, running .js files with arguments, node -e and node -p, adding JavaScript to a web page, checking syntax with node –check, running and debugging in VS Code, and the difference between browser and Node.js code.


🗺️ Five Ways to Run JavaScript

WhereHowBest for
Browser consoleF12 › ConsoleTrying one line, inspecting a web page
Node.js REPLType node in a terminalExperimenting with language features
A .js filenode app.jsReal programs, practice questions, tests
One-line commandnode -p "..."Quick calculations in scripts and CI
A web page<script src="app.js">Code that changes a page (DOM)

In this course you will mostly run files with Node.js, because a file can be saved, edited, re-run and tested.


🖥️ Run JavaScript in the Browser Console

Definition: the console is part of the browser’s Developer Tools (DevTools). It runs any JavaScript you type, in the context of the page that is open.

  1. Open any web page, for example https://example.com.
  2. Press F12 (or Ctrl+Shift+J on Windows/Linux, Cmd+Option+J on macOS) and select the Console tab.
  3. Type an expression after the > prompt and press Enter.

⌨️ Typed in the console (one line at a time)

2 + 3
"sqatools".toUpperCase()
[1, 2, 3].map(n => n * 10)
document.title

🖥️ Output (Chrome console on example.com)

5
'SQATOOLS'
(3) [10, 20, 30]
'Example Domain'
  • The console prints the value of each expression automatically; you do not need console.log here.
  • document.title works because the console runs inside the page, where the document object exists.
  • Press Shift+Enter to write several lines before running them.

⚠️ Watch out: The first time you paste code into the Chrome console, Chrome blocks it and asks you to type allow pasting. This protects you from scams that ask people to paste code that steals their account. Only paste code you understand.


🔁 The Node.js REPL

Definition: a REPL (Read-Eval-Print Loop) reads one line, evaluates it, prints the result and waits for the next line. Start it by typing node with no file name.

⌨️ Terminal

node

🖥️ Output (REPL session)

Welcome to Node.js v26.13.0.
Type ".help" for more information.
> 2 + 3
5
> const name = "Asha"
undefined
> `Hi ${name}`
'Hi Asha'
> [1, 2, 3].map(n => n * 2)
[ 2, 4, 6 ]
> Math.max(4, 9, 2)
9
> _
9
> .exit
  • A declaration such as const name = ... prints undefined because a declaration has no value. This is normal.
  • _ (underscore) holds the result of the last expression.
  • Press Tab to autocomplete: type Math. and press Tab twice to list every Math method.
REPL commandWhat it does
.helpLists all REPL commands
.editorMulti-line editor mode; finish with Ctrl+D
.load file.jsRuns a file inside the current session
.save file.jsSaves everything you typed to a file
.exit or Ctrl+C twiceLeaves the REPL

📄 Run a JavaScript File with Node.js

For anything longer than a line, save the code in a file with the .js extension and run node <file> from the folder that contains it.

📄 greet.js

const name = process.argv[2] || "tester";
const hour = 9;

const greeting = hour < 12 ? "Good morning" : "Good afternoon";
console.log(`${greeting}, ${name}!`);

⌨️ Terminal

node greet.js

🖥️ Output

Good morning, tester!

process.argv is an array of the command-line arguments. Items 0 and 1 are the paths of node and the file, so your first own argument is process.argv[2]:

📄 greet.js

const name = process.argv[2] || "tester";
const hour = 9;

const greeting = hour < 12 ? "Good morning" : "Good afternoon";
console.log(`${greeting}, ${name}!`);

⌨️ Terminal

node greet.js Asha

🖥️ Output

Good morning, Asha!
  • || "tester" provides a default value when no argument is given.
  • The ? : (conditional operator) picks one of two strings. You will learn it in the Operators lesson.
  • Run files from the right folder: node greet.js only works if the terminal is in the folder that contains greet.js.

💡 Tip: Use node --watch greet.js while you practise. Node.js reruns the file every time you save it.


⚡ One-Line Commands: node -e and node -p

node -e (“evaluate”) runs a string of code. node -p (“print”) runs it and prints the result. Both are handy in scripts and CI pipelines.

⌨️ Terminal

node -e "console.log('Sum:', 2 + 3)"
node -p "40 + 2"
node -p "'sqatools'.toUpperCase()"

🖥️ Output

Sum: 5
42
SQATOOLS

⚠️ Watch out: Quoting differs between shells. On Windows Command Prompt use double quotes outside and single quotes inside, as shown. In PowerShell, bash and zsh, single quotes outside (node -p '40 + 2') also work.


🌍 Run JavaScript in a Web Page

Browsers run JavaScript that a page loads with the <script> tag. Create two files in the same folder:

📄 index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My first script</title>
</head>
<body>
  <h1 id="title">Hello</h1>
  <button id="btn">Click me</button>

  <script src="app.js"></script>
</body>
</html>

📄 app.js

const title = document.getElementById("title");
const button = document.getElementById("btn");

button.addEventListener("click", () => {
  title.textContent = "JavaScript is running!";
  console.log("Button clicked at", new Date().toLocaleTimeString());
});

Double-click index.html to open it, click the button, and the heading changes. Open the console (F12) to see the log line. In VS Code, the free Live Server extension reloads the page automatically when you save.

  • Put the <script> tag at the end of <body> (or use <script src="app.js" defer> in the head) so the HTML elements exist before the script looks for them.
  • document and addEventListener are browser APIs. Module 12 of this course covers the DOM in detail.

🚫 Browser Code in Node.js: “document is not defined”

The JavaScript language is the same everywhere, but the browser and Node.js provide different global objects. Running browser code with Node.js fails:

📄 page.js

const title = document.getElementById("title");
console.log(title);

⌨️ Terminal

node page.js

🖥️ Output

/home/you/js-course/page.js:1
const title = document.getElementById("title");
              ^

ReferenceError: document is not defined
    at Object.<anonymous> (/home/you/js-course/page.js:1:15)

Node.js v26.13.0

Fix: run DOM code in a browser (a web page or the console). For tests, tools such as Playwright drive a real browser for you. The reverse also happens: process, require and fs do not exist in the browser.

Available inExamples
Bothconsole, Math, JSON, setTimeout, fetch, URL, structuredClone
Browser onlywindow, document, localStorage, alert
Node.js onlyprocess, require, __dirname (CommonJS), modules such as fs and path

A script can check where it is running and behave accordingly:

📄 where.js

const where = typeof window === "undefined" ? "Node.js" : "a browser";
console.log(`This code is running in ${where}.`);
console.log("fetch available?", typeof fetch === "function");

⌨️ Terminal

node where.js

🖥️ Output

This code is running in Node.js.
fetch available? true

🔍 Check Syntax Without Running: node –check

node --check parses a file and reports syntax errors without executing it. This is useful in CI or before running a script that changes data.

📄 bad.js

console.log("missing paren"

⌨️ Terminal

node --check bad.js

🖥️ Output

/home/you/js-course/bad.js:1
console.log("missing paren"
            ^^^^^^^^^^^^^^^

SyntaxError: missing ) after argument list

Node.js v26.13.0

The caret (^^^^) points at the problem and the message says what is missing. Add the closing ) and node --check bad.js prints nothing, which means the syntax is valid.


🧑‍💻 Run and Debug in VS Code

  1. Open the built-in terminal (Ctrl+`) and type node greet.js. This is the method used throughout the course.
  2. Or open the file and press F5, then choose Node.js. VS Code runs the file with its debugger attached and shows output in the Debug Console.
  3. Click in the gutter left of a line number to set a red breakpoint. When you press F5, the program pauses there and you can hover over variables to see their values.

You will use breakpoints properly in the Console Methods and Debugging Basics lesson.


📝 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. Open the browser console on any page and print the page title and the page URL. Which two expressions do you type?

Show answer

document.title and location.href (or window.location.href). The console prints both values without console.log.

Q2. In the Node.js REPL, type 10 * 3 and then use the last result to add 5. What do you type the second time?

Show answer

Type _ + 5. The underscore holds the last result (30), so the REPL prints 35.

Q3. Write square.js that reads a number from the command line and prints its square. node square.js 7 should print 7 squared is 49.

Show answer

📄 square.js

const n = Number(process.argv[2] || 7);
console.log(`${n} squared is ${n * n}`);

🖥️ Output

7 squared is 49

Command-line arguments are strings, so Number() converts "7" to 7. The default 7 keeps the example working with no argument.

Q4. Use a one-line command to print the current year without creating a file.

Show answer
node -p "new Date().getFullYear()"

Q5. A learner runs node app.js and gets ReferenceError: document is not defined. Explain why and give two ways to fix it.

Show answer

document is a browser object; Node.js has no web page, so the name does not exist. Fix 1: load the script in an HTML page with <script src="app.js"> and open it in a browser. Fix 2: if the code does not need the page, remove the DOM code. For automated browser checks, use a tool such as Playwright.

Q6. Write a script that prints Running in Node.js or Running in a browser depending on where it runs.

Show answer

📄 env.js

if (typeof window === "undefined") {
  console.log("Running in Node.js");
} else {
  console.log("Running in a browser");
}

🖥️ Output

Running in Node.js

typeof on an undeclared name returns "undefined" instead of throwing an error, so this check is safe in both places.


🧠 MCQ Quiz: Run JavaScript: Console, REPL, Files

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 does REPL stand for?
  2. How do you start the Node.js REPL?
  3. In the REPL, what does _ contain?
  4. Which command prints the result of an expression?
  5. With node greet.js Asha, where is "Asha"?
  6. Why does node app.js fail with document is not defined?
  7. What does node --check file.js do?
  8. Where should a <script> tag that changes page elements usually go?
  9. Which of these exists in both the browser and Node.js?
  10. Why does Chrome ask you to type allow pasting in the console?

💼 Interview Questions and Answers

Q1. What is the difference between running JavaScript in the browser and in Node.js?

The language (ECMAScript) is the same, but the host APIs differ. Browsers provide the DOM (document), window, storage and rendering, and run code in a sandbox. Node.js provides file system, network servers, process and the module system, with no DOM. Code that uses only language features and shared APIs (fetch, timers, URL) runs in both.

Q2. How do you pass input to a Node.js script, for example test data or an environment name?

  • Command-line arguments: process.argv, or util.parseArgs() for named flags such as --env=qa.
  • Environment variables: process.env.BASE_URL, often loaded from a .env file with node --env-file=.env.
  • Files: read JSON or CSV test data with fs.

Q3. A script works when you run it from its folder but fails in CI with “Cannot find module”. What is the likely cause?

Paths are resolved from the current working directory. CI may run the command from the repository root, so node app.js or a relative file path points to the wrong place. Fix it by running from the right folder (working-directory in GitHub Actions), using an npm script, or building paths from the script location (__dirname or import.meta.dirname).

Q4. What is the purpose of defer on a script tag?

<script defer src="app.js"> downloads the script in parallel while the HTML is parsed, then runs it after parsing has finished and in document order. The script can safely access all elements, and the page is not blocked while the file downloads.


❓ Frequently Asked Questions

🤔 What is the easiest way to run JavaScript?

Open your browser, press F12, choose Console and type code. For anything longer than a line, save a .js file and run it with node file.js.

🤔 Can I run JavaScript without installing anything?

Yes. Every browser runs JavaScript in its console and in web pages. You need Node.js only to run files from the terminal.

🤔 Why does the REPL print undefined after my line?

Statements such as const x = 5 or a console.log() call do not produce a value, so the REPL prints undefined. Your code still ran.

🤔 How do I run a JavaScript file in VS Code?

Open the terminal with Ctrl+` and type node yourfile.js, or press F5 and choose Node.js to run it with the debugger.


🏁 Summary

  • Use the browser console for quick checks on a page, the Node.js REPL for experiments, and .js files for real programs.
  • node file.js runs a file; process.argv holds command-line arguments.
  • node -p prints an expression’s result; node -e runs code; node --check validates syntax.
  • Web pages load JavaScript with <script src> at the end of the body or with defer.
  • Browser APIs such as document do not exist in Node.js, and Node.js APIs such as process do not exist in the browser.

Next, continue with Lesson 4: Syntax, Comments and Strict Mode.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Install JavaScript: Set Up Node.js and VS Code (Windows, macOS, Linux)

You do not install “JavaScript” itself. You install a runtime that runs JavaScript (Node.js) and an editor to write it in (VS Code). In this lesson you will install Node.js 26 LTS and npm, verify them, configure VS Code with the right extensions and settings, and create and run your first JavaScript project. The same setup is used in every lesson of this course and by Playwright, Cypress and Jest.

📖 What You’ll Learn: what Node.js, npm and VS Code are, LTS versus Current releases, installing on Windows, macOS and Linux (installer, winget, Homebrew, nvm), verifying the install, configuring VS Code, creating a project with npm init, npm scripts, watch mode and fixing the most common setup errors.


🧩 What You Will Install and Why

ToolWhat it isWhy you need it
Node.jsA JavaScript runtime built on Chrome’s V8 engineRuns .js files on your computer, outside the browser
npmNode Package Manager, installed with Node.jsInstalls libraries (Playwright, Jest, ESLint) and runs project scripts
VS CodeA free code editor from MicrosoftAutocomplete, debugging, a built-in terminal and extensions

Definition: an LTS (Long-Term Support) release is a Node.js version that receives bug and security fixes for about 30 months. Current releases get the newest features first but are supported for a shorter time. Always pick LTS for learning and for test projects.

Release lineStatus (checked 23 November 2026)Use it?
Node.js 26 “Lithium”Active LTSYes, recommended for this course
Node.js 24 “Krypton”Maintenance LTS (security fixes)OK if already installed
Node.js 22 “Jod”Maintenance LTS until April 2027OK, but plan to upgrade
Node.js 27Current (pre-release)No, not for learning

📌 Note: Every example in this course was run on Node.js v26.13.0 with npm 11.20.0. Node.js 22 or later runs all of them.


🪟 Install Node.js on Windows

Option 1: the official installer (easiest)

  1. Open nodejs.org and download the LTS Windows Installer (.msi) for your system (x64 for most PCs, ARM64 for Snapdragon laptops).
  2. Run the installer. Accept the licence and keep the default folder C:\Program Files\nodejs\.
  3. On the “Custom Setup” screen keep Add to PATH selected. This lets you type node in any terminal.
  4. The “Tools for Native Modules” checkbox is optional. Leave it unticked unless you need to compile native packages.
  5. Finish the installer, then close and reopen every terminal and VS Code window so they see the new PATH.

Option 2: winget (one command)

Windows 10 and 11 include the winget package manager. Run this in PowerShell or Command Prompt:

⌨️ Terminal

winget install OpenJS.NodeJS.LTS

💡 Tip: If you need several Node.js versions (for example one project on 22 and another on 26), use a version manager such as fnm or nvm-windows instead of the installer.


🍎 Install Node.js on macOS

Option 1: the official installer

Download the LTS macOS Installer (.pkg) from nodejs.org, open it and follow the steps. It installs node and npm into /usr/local/bin.

Option 2: Homebrew

⌨️ Terminal

brew install node

⚠️ Watch out: brew install node installs the newest release line, which may be a Current (non-LTS) version. To stay on LTS with Homebrew, install the versioned formula, for example brew install node@26, or use nvm (below).


🐧 Install Node.js on Linux (and macOS) with nvm

nvm (Node Version Manager) installs Node.js inside your home folder, so you never need sudo, and lets you switch versions per project.

  1. Copy the install command from the nvm README (it is a one-line curl ... | bash script) and run it in your terminal.
  2. Close and reopen the terminal so the nvm command is loaded.
  3. Install and select the latest LTS version:

⌨️ Terminal

nvm install --lts
nvm use --lts
nvm alias default lts/*

The last command makes the LTS version the default in every new terminal.


✅ Verify the Installation

Open a new terminal (PowerShell, Command Prompt, or Terminal on macOS/Linux) and check the versions:

⌨️ Terminal

node -v
npm -v

🖥️ Output

v26.13.0
11.20.0

Your patch numbers may be higher, which is fine. Now run one line of JavaScript straight from the terminal with node -p (“print”):

⌨️ Terminal

node -p "process.platform + ' ' + process.arch"

🖥️ Output (on Windows)

win32 x64

On a Mac with Apple silicon you would see darwin arm64, and on most Linux PCs linux x64.


📁 Create and Run Your First JavaScript Project

A Node.js project is just a folder with a package.json file. package.json stores the project name, its scripts and the packages it depends on.

⌨️ Terminal

mkdir js-course
cd js-course
npm init -y

🖥️ Output

Wrote to C:\Users\you\js-course\package.json:

{
  "name": "js-course",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type": "commonjs"
}
  • -y accepts all default answers, so npm does not ask questions.
  • "type": "commonjs" means .js files in this folder use the CommonJS module system (require). You will learn about ES modules (import) in Module 11.

Create a file called app.js in the folder with this content, then run it:

📄 app.js

console.log("Hello from Node.js", process.version);

⌨️ Terminal

node app.js

🖥️ Output

Hello from Node.js v26.13.0

Add npm scripts

npm scripts are named commands stored in package.json. Add two scripts with npm pkg set (or edit the file by hand):

⌨️ Terminal

npm pkg set scripts.start="node app.js" scripts.dev="node --watch app.js"

📄 package.json (scripts part)

{
  "name": "js-course",
  "version": "1.0.0",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js",
    "dev": "node --watch app.js"
  },
  "type": "commonjs"
}

⌨️ Terminal

npm start

🖥️ Output

> js-course@1.0.0 start
> node app.js

Hello from Node.js v26.13.0

npm run dev starts watch mode: Node.js reruns app.js every time you save it, which is ideal while practising. Press Ctrl+C to stop it.

⌨️ Terminal

npm run dev

🖥️ Output

Hello from Node.js v26.13.0
Completed running 'app.js'. Waiting for file changes before restarting...

🧑‍💻 Install and Configure VS Code

  1. Download VS Code from code.visualstudio.com and install it. On Windows, tick Add “Open with Code” action and Add to PATH.
  2. Open your project: File › Open Folder… and choose js-course, or type code . in a terminal inside the folder.
  3. Open the built-in terminal with Ctrl+` (back-tick). It starts in your project folder, so node app.js works straight away.

Recommended extensions

ExtensionIDWhat it does
ESLintdbaeumer.vscode-eslintUnderlines likely bugs (set up in Module 11)
Prettier – Code formatteresbenp.prettier-vscodeFormats code automatically on save
Error Lens (optional)usernamehw.errorlensShows errors inline, next to the code

Install an extension from the Extensions view (Ctrl+Shift+X), or from the terminal:

⌨️ Terminal

code --install-extension esbenp.prettier-vscode
code --install-extension dbaeumer.vscode-eslint

Recommended settings

Open Command Palette (Ctrl+Shift+P) › Preferences: Open User Settings (JSON) and add:

📄 settings.json

{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.tabSize": 2,
  "files.autoSave": "onFocusChange",
  "javascript.updateImportsOnFileMove.enabled": "always"
}
  • formatOnSave + Prettier: your code is tidied every time you save.
  • tabSize: 2: two-space indentation is the JavaScript convention.
  • autoSave: files save when you switch to the terminal, so you never run an old version.

💡 Tip: Turn on type checking in plain JavaScript files by adding // @ts-check as the first line. VS Code then underlines mistakes such as calling a method that does not exist, using the TypeScript engine it already includes.


🛠️ Fix Common Setup Errors

“node is not recognized” on Windows

🖥️ Output

'node' is not recognized as an internal or external command,
operable program or batch file.

Cause: the terminal was opened before Node.js was installed, or “Add to PATH” was unticked. Fix: close every terminal and VS Code window and open them again. If it still fails, rerun the installer and keep Add to PATH selected.

“command not found: node” on macOS or Linux

Fix: open a new terminal. With nvm, run nvm use --lts; if nvm itself is not found, the install script could not update your shell profile (~/.zshrc or ~/.bashrc). Follow the “Troubleshooting” section of the nvm README.

npm blocked in PowerShell

🖥️ Output

npm : File C:\Program Files\nodejs\npm.ps1 cannot be loaded because running scripts is disabled on this system.

Fix: allow scripts signed or created on your computer for your user only, then reopen PowerShell:

⌨️ Terminal

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned

If your company manages this setting, use Command Prompt instead, where npm runs npm.cmd and is not affected.

“Cannot find module” when running a file

📄 app.js

console.log("this file exists");

⌨️ Terminal

node ap.js

🖥️ Output

node:internal/modules/cjs/loader:1607
  throw err;
  ^

Error: Cannot find module 'C:\Users\you\js-course\ap.js'
    at Module._resolveFilename (node:internal/modules/cjs/loader:1603:15)
    ... (more Node.js internal lines)
    at node:internal/main/run_main_module:33:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

Node.js v26.13.0

Cause: a typo in the file name, or the terminal is in a different folder. Fix: check the name and run pwd (macOS/Linux/PowerShell) or cd (Command Prompt) to see the current folder.


📝 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. Which command prints only the installed Node.js version, and which prints the npm version?

Show answer

node -v (or node --version) prints the Node.js version, for example v26.13.0. npm -v prints the npm version, for example 11.20.0.

Q2. Without creating a file, use node -p to print the result of 7 * 6.

Show answer
node -p "7 * 6"

-p evaluates the expression and prints the result: 42. node -e runs code without printing the result, so you would need node -e "console.log(7 * 6)".

Q3. Write info.js that prints the Node.js version, the operating system and the CPU architecture on three lines.

Show answer

📄 info.js

console.log("Node:", process.version);
console.log("OS:", process.platform);
console.log("CPU:", process.arch);

🖥️ Output

Node: v26.13.0
OS: win32
CPU: x64

Q4. Add an npm script called hello that runs node info.js, then run it. What exactly do you type?

Show answer
npm pkg set scripts.hello="node info.js"
npm run hello

Only start and test can be run without the word run; every other script needs npm run <name>.

Q5. A teammate on Windows sees 'node' is not recognized as an internal or external command right after installing Node.js. List two likely causes and fixes.

Show answer
  • The terminal was already open during the install, so it has the old PATH. Fix: close and reopen the terminal (and VS Code).
  • “Add to PATH” was unticked in the installer. Fix: rerun the installer and keep it selected, or add C:\Program Files\nodejs\ to PATH.

Q6. Why is node --watch app.js useful while learning, and how do you stop it?

Show answer

Watch mode reruns the file automatically each time you save it, so you see the new output without typing the command again. Stop it with Ctrl+C.


🧠 MCQ Quiz: Install Node.js and VS Code

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 does LTS stand for in Node.js releases?
  2. Which Node.js line was the Active LTS in November 2026?
  3. How do you install npm?
  4. What does npm init -y create?
  5. Which command runs a script named dev from package.json?
  6. What does node --watch app.js do?
  7. Why might brew install node not give you an LTS version?
  8. Which VS Code shortcut opens the built-in terminal?
  9. What is the most likely fix for 'node' is not recognized right after installing?
  10. What does "type": "commonjs" in package.json mean?

💼 Interview Questions and Answers

Q1. What is Node.js, and how is it different from JavaScript?

JavaScript is the language. Node.js is a runtime that executes JavaScript outside the browser, built on the V8 engine plus libuv for asynchronous I/O. It adds APIs such as fs, http and process, and has no DOM. Test runners like Playwright and Jest run on Node.js.

Q2. Why should a test automation project pin its Node.js version, and how?

Different Node.js versions can change behaviour (for example module loading or built-in APIs), so CI and every laptop should use the same major version to avoid “works on my machine” failures. Pin it with an .nvmrc or .node-version file (for example 26), the "engines" field in package.json, and actions/setup-node with node-version-file in GitHub Actions.

Q3. What is the difference between npm, npx and nvm?

  • npm installs packages and runs scripts from package.json.
  • npx runs a package’s command without a global install, for example npx playwright test.
  • nvm installs and switches between Node.js versions. It is not part of Node.js.

Q4. What is package.json used for?

It is the project manifest: name and version, scripts (named commands such as test), dependencies and devDependencies with version ranges, the module type ("type"), and the engines field. npm install reads it to install packages, and package-lock.json records the exact versions installed.

Q5. A CI job fails with “npm: command not found” but works locally. How do you investigate?

  1. Check that the job installs Node.js before using it (for example actions/setup-node or a Docker image such as node:26).
  2. Print node -v and npm -v as the first step to confirm the versions.
  3. If a version manager is used, make sure its shell setup is loaded in the CI shell (non-interactive shells may skip ~/.bashrc).
  4. Pin the version with .nvmrc so CI and local runs match.

❓ Frequently Asked Questions

🤔 Do I need to install JavaScript separately?

No. Browsers already include a JavaScript engine. To run JavaScript files on your computer you install Node.js, which includes the V8 engine and npm.

🤔 Which Node.js version should I install for Playwright?

Install the current LTS (Node.js 26 in November 2026). Playwright supports the active and maintenance LTS releases.

🤔 Can I use another editor instead of VS Code?

Yes. WebStorm, Sublime Text, Vim or any editor works. This course shows VS Code because it is free, popular and has the best JavaScript and Playwright extensions.

🤔 How do I update Node.js later?

Download the newer LTS installer and run it (it replaces the old version), run winget upgrade OpenJS.NodeJS.LTS on Windows, or with nvm run nvm install --lts and nvm alias default lts/*.


🏁 Summary

  • You run JavaScript files with Node.js; npm comes with it. Always choose the LTS release (Node.js 26 in 2026).
  • Install with the official installer, winget, Homebrew (node@26) or nvm, then verify with node -v and npm -v.
  • A project is a folder with package.json; create it with npm init -y and add npm scripts.
  • node --watch reruns your file on every save.
  • Configure VS Code with Prettier, ESLint, format on save and 2-space indentation.

Next, continue with Lesson 3: Run JavaScript: Console, REPL, Files.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

What Is JavaScript? Features, History, Engines and Uses

JavaScript is the programming language of the web, and today it also runs servers, command-line tools and test automation frameworks such as Playwright and Cypress. In this first lesson you will learn what JavaScript is, where it runs, how it is standardised and why it is the best first language for anyone who wants to build or test web applications.

📖 What You’ll Learn: what JavaScript is, its key features, its history and versions (ECMAScript), engines and runtimes (V8, Node.js), what you can build with it, how it compares with Java, TypeScript and Python, and your first program.


🌐 What Is JavaScript?

Definition: JavaScript is a high-level, dynamically typed, multi-paradigm programming language. It was created to make web pages interactive, and it is the only programming language that every web browser runs natively.

Let us unpack the important words in that definition:

  • High-level: you write readable code; memory is managed for you by a garbage collector.
  • Dynamically typed: a variable can hold any type of value, and types are checked while the program runs, not before.
  • Multi-paradigm: you can write procedural, object-oriented or functional code.
  • Single-threaded with an event loop: one piece of your code runs at a time, but slow work such as network calls runs in the background without blocking.
  • Just-in-time (JIT) compiled: modern engines compile JavaScript to machine code while it runs, which makes it fast.

Here is the smallest useful JavaScript program. console.log() prints a value to the console (the terminal in Node.js, or the DevTools console in a browser).

📄 hello.js

console.log("Hello, JavaScript!");
console.log("2 + 3 =", 2 + 3);

⌨️ Terminal

node hello.js

🖥️ Output

Hello, JavaScript!
2 + 3 = 5

You will install Node.js in the next lesson. Until then you can paste the code into your browser console: press F12 in Chrome or Edge and open the Console tab.


⭐ Key Features of JavaScript

These features explain why JavaScript is everywhere:

FeatureWhat it means for you
Runs in every browserNo install is needed to run JavaScript on a web page.
Runs outside the browserNode.js, Deno and Bun run JavaScript on servers and your computer.
Dynamic typingQuick to write; types are checked at run time.
First-class functionsFunctions are values: store them in variables and pass them to other functions.
Objects and prototypesObjects can inherit from other objects; the class syntax builds on this.
Asynchronous by designPromises and async/await handle network and file work without freezing.
Huge ecosystemnpm, the JavaScript package registry, hosts millions of free packages.

The next example shows dynamic typing and first-class functions in action. typeof returns the type of a value as a string.

📄 features.js

let value = 42;
console.log(typeof value); // number

value = "forty-two";        // the same variable now holds a string
console.log(typeof value);

// A function stored in a variable and passed to another function
const double = (n) => n * 2;
console.log([1, 2, 3].map(double));

⌨️ Terminal

node features.js

🖥️ Output

number
string
[ 2, 4, 6 ]
  • value first holds a number and then a string. JavaScript allows this because it is dynamically typed.
  • double is an arrow function stored in a constant.
  • map(double) passes the function to an array method, which calls it once for each item.

📜 A Short History: From Netscape to ECMAScript 2026

Brendan Eich created JavaScript at Netscape in 1995, in about ten days. It was first called Mocha, then LiveScript, and was renamed JavaScript for marketing reasons. Despite the name, it is not related to Java.

To stop browsers from creating incompatible versions, JavaScript was standardised by Ecma International as ECMAScript. The committee that evolves the language is called TC39. “JavaScript” is the language you write; “ECMAScript” is the specification that engines implement.

VersionYearHighlights
ES11997First standard
ES31999Regular expressions, try/catch
ES52009Strict mode, JSON, array methods such as forEach and map
ES2015 (ES6)2015let/const, arrow functions, classes, modules, promises, template literals
ES20172017async/await
ES20202020Optional chaining ?., nullish coalescing ??, BigInt
ES2022 to ES20252022–2025Array.prototype.at(), private class fields, Object.groupBy, new Set methods
ES20262026The current edition. A new edition is published every June.

💡 Tip: Since 2015 a new ECMAScript edition comes out every year, so people name versions by year (ES2020, ES2026) instead of by number. When someone says “modern JavaScript”, they usually mean ES2015 and later.


⚙️ JavaScript Engines and Runtimes

Definition: a JavaScript engine is the program that reads and executes JavaScript code. A runtime is an engine plus extra features (APIs) for a particular environment.

EngineUsed by
V8Google Chrome, Microsoft Edge, Node.js, Deno
SpiderMonkeyMozilla Firefox
JavaScriptCoreApple Safari, Bun

The language is the same everywhere, but the extra APIs differ. A browser gives you document and window for the web page. Node.js gives you process, the file system (fs) and other server features instead. This program prints details about the Node.js runtime it runs on:

📄 runtime.js

console.log("Node.js version:", process.version);
console.log("V8 engine version:", process.versions.v8);
console.log("Running in a browser?", typeof window !== "undefined");

⌨️ Terminal

node runtime.js

🖥️ Output

Node.js version: v26.13.0
V8 engine version: 14.6.202.34-node.40
Running in a browser? false
  • process exists only in Node.js. In a browser this line would fail with ReferenceError: process is not defined.
  • typeof window is "undefined" in Node.js because there is no browser window.

🧰 What Can You Build with JavaScript?

  • Interactive websites: menus, forms, validation, live search, single-page apps with React, Angular or Vue.
  • Back-end servers and APIs with Node.js and frameworks such as Express or Fastify.
  • Test automation: Playwright, Cypress, WebdriverIO, Jest and Vitest all use JavaScript or TypeScript.
  • Command-line tools and build tools (npm, Vite, ESLint are written in JavaScript).
  • Desktop and mobile apps with Electron (VS Code is built with it) and React Native.

A small, realistic example: calculate a shopping-cart total, the kind of logic a tester often checks.

📄 cart.js

const cart = [
  { item: "Keyboard", price: 49.99, qty: 1 },
  { item: "Mouse", price: 19.5, qty: 2 },
];

let total = 0;
for (const line of cart) {
  total += line.price * line.qty;
}

console.log(`Items: ${cart.length}`);
console.log(`Total: $${total.toFixed(2)}`);

⌨️ Terminal

node cart.js

🖥️ Output

Items: 2
Total: $88.99
  • cart is an array of objects, the most common data shape in JavaScript.
  • for...of loops over each line of the cart.
  • toFixed(2) formats the number with two decimal places. The template literal (back-ticks) inserts values with ${...}.

⚖️ JavaScript vs Java vs TypeScript vs Python

JavaScriptTypeScriptJavaPython
TypingDynamicStatic (checked before running)StaticDynamic
Runs in the browserYes, nativelyAfter compiling to JavaScriptNoNo
Main useWeb front end, Node.js back end, testingLarge JavaScript projectsEnterprise back ends, AndroidData, scripting, testing
Test toolsPlaywright, Cypress, JestPlaywright, CypressSelenium, TestNGPytest, Playwright, Selenium

TypeScript is JavaScript plus type annotations. Every JavaScript program is valid TypeScript, so learning JavaScript first is the right order. When you are ready, the Playwright with TypeScript tutorial builds on this course.


🧪 JavaScript for Testers: Your First Check

Testing is comparing what a program does with what it should do. Node.js has a built-in assert module for that. This test checks a small discount function:

📄 discount.test.js

const assert = require("node:assert/strict");

function discount(price, percent) {
  return price - (price * percent) / 100;
}

assert.equal(discount(200, 10), 180);
assert.equal(discount(99.99, 0), 99.99);
console.log("All checks passed");

⌨️ Terminal

node discount.test.js

🖥️ Output

All checks passed

When a check fails, Node.js stops and shows you the expected and actual values. Here the function has a bug: it adds the discount instead of subtracting it.

📄 discount-bug.test.js

const assert = require("node:assert/strict");

function discount(price, percent) {
  return price + (price * percent) / 100; // bug
}

assert.equal(discount(200, 10), 180);

⌨️ Terminal

node discount-bug.test.js

🖥️ Output

node:internal/assert/utils:146
  throw error;
  ^

AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:

220 !== 180

    at Object.<anonymous> (/home/you/js-course/discount-bug.test.js:7:8)
 {
  generatedMessage: true,
  code: 'ERR_ASSERTION',
  actual: 220,
  expected: 180,
  operator: 'strictEqual',
  diff: 'simple'
}

Node.js v26.13.0

⚠️ Watch out: Read error messages from the top. AssertionError tells you a check failed, 220 !== 180 shows actual versus expected, and the line number points to the failing check. Test frameworks such as Playwright and Jest print the same kind of message.


🚫 A Common Beginner Error: JavaScript Is Case-Sensitive

console, Console and CONSOLE are three different names. Only the lowercase one exists:

📄 case.js

Console.log("Hello");

⌨️ Terminal

node case.js

🖥️ Output

/home/you/js-course/case.js:1
Console.log("Hello");
^

ReferenceError: Console is not defined
    at Object.<anonymous> (/home/you/js-course/case.js:1:1)

Node.js v26.13.0

Fix: write console.log in lowercase. A ReferenceError always means “I cannot find anything with this name”; check the spelling and the capital letters first.


📝 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 a program that prints Hello, JavaScript! on the first line and My name is Asha on the second line.

Show answer

📄 practice1.js

console.log("Hello, JavaScript!");
console.log("My name is Asha");

🖥️ Output

Hello, JavaScript!
My name is Asha

Each console.log() call prints one line.

Q2. Print the Node.js version and the V8 engine version on one line, separated by | .

Show answer

📄 practice2.js

console.log(process.version + " | V8 " + process.versions.v8);

🖥️ Output

v26.13.0 | V8 14.6.202.34-node.40

Your numbers may differ; any Node.js 22 or later works for this course.

Q3. Print the type of each value: 42, "42", true, undefined and null. Which result surprises you?

Show answer

📄 practice3.js

console.log(typeof 42);
console.log(typeof "42");
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof null);

🖥️ Output

number
string
boolean
undefined
object

typeof null returns "object". This is a bug from the first version of JavaScript that was never fixed, because fixing it would break old websites. null is really its own primitive type.

Q4. This code throws an error. Find and fix the mistake.

console.Log("Ready");
Show answer

The method name is log in lowercase. console.Log is undefined, so calling it throws TypeError: console.Log is not a function.

📄 practice4.js

console.log("Ready");

🖥️ Output

Ready

Q5. Three items cost 12.5, 7.25 and 30. Print the total with two decimal places, like Total: 49.75.

Show answer

📄 practice5.js

const total = 12.5 + 7.25 + 30;
console.log("Total: " + total.toFixed(2));

🖥️ Output

Total: 49.75

Q6. Write a check with node:assert/strict that proves Math.max(3, 9, 4) returns 9, and print Max check passed if it does.

Show answer

📄 practice6.js

const assert = require("node:assert/strict");

assert.equal(Math.max(3, 9, 4), 9);
console.log("Max check passed");

🖥️ Output

Max check passed

If the check failed, Node.js would throw an AssertionError and the last line would never run.


🧠 MCQ Quiz: What Is JavaScript?

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. Who created JavaScript, and in which year?
  2. What is ECMAScript?
  3. Which JavaScript engine does Node.js use?
  4. What does typeof null return?
  5. Which statement about JavaScript and Java is true?
  6. What does “dynamically typed” mean?
  7. Which object exists in Node.js but not in a web page?
  8. What happens when you run Console.log("Hi")?
  9. Since 2015, how often is a new ECMAScript edition released?
  10. Which test automation tool is not written for JavaScript/TypeScript?

💼 Interview Questions and Answers

Q1. What is JavaScript, and where does it run?

JavaScript is a high-level, dynamically typed, multi-paradigm language standardised as ECMAScript. It runs in every web browser (engines such as V8, SpiderMonkey and JavaScriptCore) and outside the browser in runtimes such as Node.js, Deno and Bun. The language is the same everywhere; the available APIs differ, for example document in browsers and fs in Node.js.

Q2. Is JavaScript interpreted or compiled?

Both. Engines start by interpreting the code (or compiling it quickly to bytecode) so it starts fast, then a just-in-time (JIT) compiler turns frequently run (“hot”) code into optimised machine code. V8 uses the Ignition interpreter and the TurboFan optimising compiler. So the honest answer is “JIT-compiled”, and there is no separate compile step for the developer.

Q3. What is the difference between JavaScript and ECMAScript?

ECMAScript is the specification (ECMA-262) published by Ecma International and evolved by the TC39 committee. JavaScript is the most popular implementation of that specification, plus host APIs such as the DOM or Node.js modules, which are not part of ECMAScript.

Q4. JavaScript is single-threaded. How can it handle many network requests at once?

Your JavaScript code runs on one thread, but the runtime (the browser or Node.js) performs slow I/O such as network and disk work in the background. When the work finishes, a callback is queued, and the event loop runs it when the call stack is empty. Promises and async/await are built on this model. You will study it in the Event Loop lesson.

Q5. Why should a tester learn JavaScript before Playwright or Cypress?

Test scripts are JavaScript or TypeScript programs. Locators, assertions and page objects all use variables, functions, objects, classes and especially async/await. Without those basics, flaky tests caused by a missing await or a wrong comparison are hard to debug. Knowing the language also lets you write helpers for test data, API calls and reports.

Q6. What is the difference between JavaScript and TypeScript?

TypeScript is a superset of JavaScript that adds static types. The TypeScript compiler checks types before the code runs and then removes them, producing plain JavaScript. Any JavaScript code is valid TypeScript. TypeScript catches mistakes earlier and gives better autocomplete, which is why most Playwright projects use it.


❓ Frequently Asked Questions

🤔 Is JavaScript hard to learn for beginners?

No. You can run JavaScript in any browser without installing anything, and the basic syntax is short. The harder parts, such as asynchronous code and this, come later in this course after you know the basics.

🤔 Is JavaScript the same as Java?

No. They are different languages. The name was a marketing decision in 1995. Java is statically typed and runs on the JVM; JavaScript is dynamically typed and runs in browsers and Node.js.

🤔 Do I need to learn HTML and CSS before JavaScript?

Not for this course. Modules 1 to 11 run JavaScript in Node.js. Basic HTML helps for Module 12 (DOM and browser), which explains the HTML it uses.

🤔 Which JavaScript version should I learn in 2026?

Learn modern JavaScript (ES2015 and later, up to ES2026). All current browsers and Node.js 22 or later support it, and that is what this course teaches.


🏁 Summary

  • JavaScript is a high-level, dynamically typed, multi-paradigm language that runs in every browser and, with Node.js, outside the browser.
  • ECMAScript is the standard; TC39 releases a new edition every year, and ES2026 is the current one.
  • Engines such as V8 run the code; runtimes such as Chrome and Node.js add their own APIs.
  • JavaScript powers web apps, servers, CLI tools and test frameworks such as Playwright and Cypress.
  • It is case-sensitive: ReferenceError usually means a misspelled or wrongly capitalised name.

Next, continue with Lesson 2: Install Node.js and VS Code.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript async/await Explained: Write Asynchronous Code That Reads Like Sync

async and await let you write asynchronous code that reads top to bottom like ordinary code, while it still runs without blocking. Every Playwright test is an async function, and almost every line in it starts with await. In this lesson you will learn exactly what async and await do, how to handle errors with try...catch, when to run awaits in sequence and when in parallel, how to use them in loops and at the top level of modules, and the mistakes that cause most flaky tests.

📖 What You’ll Learn: async functions and their return values, await and what it does to the function, converting promise chains to async/await, error handling with try/catch/finally, sequential versus parallel awaits, await in loops (for…of versus forEach and map), async arrow functions and methods, top-level await in ES modules, return versus return await, common mistakes, and async patterns in Playwright tests.


⚙️ async Functions

Definition: an async function is a function declared with the async keyword. It always returns a promise: a returned value becomes the promise’s fulfilled value, and a thrown error becomes its rejection.

📄 async-function.js

async function getStatus() {
  return "ok";                     // wrapped in a fulfilled promise
}

async function failStatus() {
  throw new Error("service down"); // becomes a rejected promise
}

const p = getStatus();
console.log(p instanceof Promise);
p.then((value) => console.log("value:", value));
failStatus().catch((err) => console.log("rejected:", err.message));

⌨️ Terminal

node async-function.js

🖥️ Output

true
value: ok
rejected: service down

You can write async functions as declarations, expressions, arrow functions and methods:

📄 Forms of async functions

async function load() {}
const load2 = async function () {};
const load3 = async () => {};
const page = { async open() {} };
class Api { async get(path) {} }

⏸️ await: Pause Until a Promise Settles

Definition: await promise pauses the current async function until the promise settles. If it fulfils, await returns the value; if it rejects, await throws the error. Only the async function pauses: the rest of the program keeps running.

📄 await.js

const delay = (ms, value) => new Promise((r) => setTimeout(() => r(value), ms));

async function main() {
  console.log("1. start");
  const user = await delay(20, { name: "Asha" });   // pauses here
  console.log("3. got user:", user.name);
  const orders = await delay(20, [101, 102]);
  console.log("4. got orders:", orders);
  return orders.length;
}

main().then((count) => console.log("5. main resolved with", count));
console.log("2. main is paused, other code keeps running");

⌨️ Terminal

node await.js

🖥️ Output

1. start
2. main is paused, other code keeps running
3. got user: Asha
4. got orders: [ 101, 102 ]
5. main resolved with 2

⚠️ Watch out: await is only valid inside an async function (or at the top level of an ES module). Using it in a normal function is a syntax error:

📄 await-error.js

function notAsync() {
  const value = await Promise.resolve(1);
  return value;
}

⌨️ Terminal

node await-error.js

🖥️ Output

/home/you/js-course/await-error.js:2
  const value = await Promise.resolve(1);
                ^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules

Node.js v26.13.0

🔁 From Promise Chains to async/await

The same login → cart → checkout flow, first as a promise chain, then with async/await:

📄 convert.js

const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const api = {
  login: (u) => delay(5, { token: `t-${u}` }),
  getCart: (t) => delay(5, { items: [499, 1299] }),
  checkout: (cart) => delay(5, { orderId: 451, total: cart.items.reduce((a, b) => a + b, 0) }),
};

function withThen() {
  return api.login("asha")
    .then((s) => api.getCart(s.token))
    .then((cart) => api.checkout(cart))
    .then((order) => `then: order ${order.orderId} ₹${order.total}`);
}

async function withAwait() {
  const session = await api.login("asha");
  const cart = await api.getCart(session.token);
  const order = await api.checkout(cart);
  return `await: order ${order.orderId} ₹${order.total}`;
}

withThen().then(console.log).then(withAwait).then(console.log);

⌨️ Terminal

node convert.js

🖥️ Output

then: order 451 ₹1798
await: order 451 ₹1798

The async version keeps every intermediate value in a named variable, which is easy to read, log and inspect in a debugger.


🛡️ Error Handling with try…catch…finally

Because a rejected promise makes await throw, normal try...catch works with asynchronous code, and finally runs cleanup in all cases:

📄 try-catch.js

const delay = (ms) => new Promise((r) => setTimeout(r, ms));

async function placeOrder(total) {
  await delay(10);
  if (total <= 0) throw new Error(`Invalid total: ${total}`);
  return { orderId: 451, total };
}

async function checkout(total) {
  console.log(`open session for total ${total}`);
  try {
    const order = await placeOrder(total);
    console.log("placed:", order.orderId);
  } catch (err) {
    console.log("checkout failed:", err.message);
  } finally {
    console.log("close session");
  }
}

(async () => {
  await checkout(1299);
  await checkout(0);
})();

⌨️ Terminal

node try-catch.js

🖥️ Output

open session for total 1299
placed: 451
close session
open session for total 0
checkout failed: Invalid total: 0
close session

💡 Tip: Handle errors where you can do something useful. In tests, usually let them propagate: the test runner catches them and marks the test as failed with the full message and stack trace.


🏎️ Sequential vs Parallel Awaits

Each await waits before the next line runs. That is correct when steps depend on each other, but wasteful for independent work. Start independent promises first, then await them together with Promise.all (see the Promise methods lesson):

📄 parallel.js

const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const ms = (start) => Math.round((Date.now() - start) / 100) * 100;

async function main() {
  let t = Date.now();
  const profile = await delay(100, "profile");
  const orders = await delay(100, "orders");          // waits for profile first
  console.log("sequential:", profile, orders, `~${ms(t)} ms`);

  t = Date.now();
  const [profile2, orders2] = await Promise.all([delay(100, "profile"), delay(100, "orders")]);
  console.log("parallel:  ", profile2, orders2, `~${ms(t)} ms`);
}
main();

⌨️ Terminal

node parallel.js

🖥️ Output

sequential: profile orders ~200 ms
parallel:   profile orders ~100 ms

🔂 await Inside Loops

This is where many bugs live. The rules:

PatternBehaviourUse when
for (const x of items) { await f(x); }One at a time, in orderSteps must not overlap (UI actions, ordered API calls)
await Promise.all(items.map(async (x) => f(x)))All at once, waits for allIndependent work
items.forEach(async (x) => { await f(x); })Starts all, waits for noneNever in async code

📄 loops.js

const delay = (ms) => new Promise((r) => setTimeout(r, ms));
const done = [];
const processItem = async (id) => { await delay(10); done.push(id); };

async function main() {
  [1, 2, 3].forEach(async (id) => { await processItem(id); });
  console.log("after forEach, done:", [...done]);        // nothing finished yet!
  await delay(30);
  done.length = 0;

  for (const id of [1, 2, 3]) await processItem(id);
  console.log("after for...of, done:", [...done]);
  done.length = 0;

  await Promise.all([1, 2, 3].map(processItem));
  console.log("after Promise.all(map), done:", [...done].sort());
}
main();

⌨️ Terminal

node loops.js

🖥️ Output

after forEach, done: []
after for...of, done: [ 1, 2, 3 ]
after Promise.all(map), done: [ 1, 2, 3 ]

⚠️ Watch out: forEach ignores the promises returned by an async callback, so the code after it runs before the work is done, and errors inside become unhandled rejections. In Playwright, locators.forEach(async (l) => await l.click()) is a classic cause of flaky tests.


🌐 Top-Level await in ES Modules

In ES modules (.mjs files, or "type": "module" in package.json), you can use await directly at the top level, without wrapping code in an async function:

📄 top-level.mjs

const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));

const config = await delay(10, { env: "qa", baseURL: "https://qa.example.com" });
console.log("config loaded before anything else:", config.env);

const [users, products] = await Promise.all([delay(10, 3), delay(10, 12)]);
console.log({ users, products });

⌨️ Terminal

node top-level.mjs

🖥️ Output

config loaded before anything else: qa
{ users: 3, products: 12 }

In CommonJS files (.js without "type": "module"), wrap the code in an async function instead, as the other examples in this lesson do: (async () => { ... })(); or a named main() with a .catch.


🔙 return vs return await

Inside an async function, return promise and return await promise usually give the same result. They differ inside try...catch: only return await lets the local catch handle a rejection.

📄 return-await.js

const failing = () => Promise.reject(new Error("upstream failed"));

async function withoutAwait() {
  try {
    return failing();          // the rejection escapes the try block
  } catch {
    return "handled locally";
  }
}

async function withAwait() {
  try {
    return await failing();    // awaited inside try: catch runs
  } catch {
    return "handled locally";
  }
}

withoutAwait().then(console.log, (e) => console.log("withoutAwait rejected:", e.message));
withAwait().then((v) => console.log("withAwait:", v));

⌨️ Terminal

node return-await.js

🖥️ Output

withAwait: handled locally
withoutAwait rejected: upstream failed

🧪 Tester Scenario: The Anatomy of an Async Test

A Playwright test body is an async arrow function, and every browser action returns a promise that must be awaited. The simulated version below runs in Node.js and shows the same structure: setup, actions, assertions and cleanup, all awaited in order.

📄 order.spec.ts (Playwright, for reference)

import { test, expect } from "@playwright/test";

test("user can place an order", async ({ page, request }) => {
  const user = await (await request.post("/api/test-users")).json();   // API setup
  await page.goto("/login");
  await page.getByLabel("Email").fill(user.email);
  await page.getByRole("button", { name: "Log in" }).click();
  await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
});

📄 async-test.js

const delay = (ms) => new Promise((r) => setTimeout(r, ms));

const fakePage = {
  url: "about:blank",
  heading: "",
  async goto(path) { await delay(10); this.url = path; this.heading = path === "/dashboard" ? "Dashboard" : "Login"; },
  async fill(label, value) { await delay(5); this[label] = value; },
  async click() { await delay(10); await this.goto("/dashboard"); },
};

async function expectHeading(page, text) {
  if (page.heading !== text) throw new Error(`Expected heading "${text}" but got "${page.heading}"`);
}

async function test(name, body) {
  try {
    await body();
    console.log(`✓ ${name}`);
  } catch (e) {
    console.log(`✗ ${name}: ${e.message}`);
  }
}

(async () => {
  await test("login with await on every step", async () => {
    await fakePage.goto("/login");
    await fakePage.fill("email", "asha@sqatools.in");
    await fakePage.click("Log in");
    await expectHeading(fakePage, "Dashboard");
  });

  await test("login with one missing await", async () => {
    await fakePage.goto("/login");
    await fakePage.fill("email", "asha@sqatools.in");
    fakePage.click("Log in");                 // missing await
    await expectHeading(fakePage, "Dashboard");
  });
})();

⌨️ Terminal

node async-test.js

🖥️ Output

✓ login with await on every step
✗ login with one missing await: Expected heading "Dashboard" but got "Login"

The second test fails because the assertion runs before the click and navigation finish. With a real browser the timing varies, so the same mistake causes a test that sometimes passes and sometimes fails.


📝 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 an async function double(n) that waits 10 ms and returns n * 2. Print await double(21).

Show answer

📄 practice1.js

const delay = (ms) => new Promise((r) => setTimeout(r, ms));
async function double(n) {
  await delay(10);
  return n * 2;
}
(async () => console.log(await double(21)))();

🖥️ Output

42

Q2. Rewrite this chain with async/await.

getUser()
  .then((user) => getOrders(user.id))
  .then((orders) => console.log(orders.length))
  .catch((err) => console.log(err.message));
Show answer

📄 practice2.js

const getUser = async () => ({ id: 7 });
const getOrders = async (id) => [{ id: 1, user: id }, { id: 2, user: id }];

async function main() {
  try {
    const user = await getUser();
    const orders = await getOrders(user.id);
    console.log(orders.length);
  } catch (err) {
    console.log(err.message);
  }
}
main();

🖥️ Output

2

Q3. Fetch three independent “resources” (each takes 50 ms) in parallel with await Promise.all and print them.

Show answer

📄 practice3.js

const load = (name) => new Promise((r) => setTimeout(() => r(name.toUpperCase()), 50));
(async () => {
  const [a, b, c] = await Promise.all([load("users"), load("orders"), load("stock")]);
  console.log(a, b, c);
})();

🖥️ Output

USERS ORDERS STOCK

Q4. Process the IDs [3, 1, 2] strictly one after another (each step waits 10 ms) and print them in that order, using for...of.

Show answer

📄 practice4.js

const delay = (ms) => new Promise((r) => setTimeout(r, ms));
(async () => {
  for (const id of [3, 1, 2]) {
    await delay(10);
    console.log("processed", id);
  }
})();

🖥️ Output

processed 3
processed 1
processed 2

Q5. Write safe(fn) that awaits fn() and returns [error, result] instead of throwing. Test it with a succeeding and a failing async function.

Show answer

📄 practice5.js

async function safe(fn) {
  try {
    return [null, await fn()];
  } catch (e) {
    return [e, null];
  }
}
(async () => {
  const [e1, r1] = await safe(async () => "ok");
  const [e2, r2] = await safe(async () => { throw new Error("boom"); });
  console.log(e1, r1, "|", e2.message, r2);
})();

🖥️ Output

null ok | boom null

Q6. This code prints 0 items saved. Fix it so it prints 3 items saved.

const save = (x) => new Promise((r) => setTimeout(() => { saved.push(x); r(); }, 10));
const saved = [];
async function main() {
  ["a", "b", "c"].forEach(async (x) => await save(x));
  console.log(saved.length, "items saved");
}
main();
Show answer

📄 practice6.js

const saved = [];
const save = (x) => new Promise((r) => setTimeout(() => { saved.push(x); r(); }, 10));
async function main() {
  await Promise.all(["a", "b", "c"].map((x) => save(x)));
  console.log(saved.length, "items saved");
}
main();

🖥️ Output

3 items saved

forEach does not wait for async callbacks. Use Promise.all with map (parallel) or a for...of loop with await (one by one).


🧠 MCQ Quiz: Async/Await

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 does an async function always return?
  2. What happens when an awaited promise rejects?
  3. Where can you use await?
  4. Does await block the whole program?
  5. Which loop correctly waits for each async step in order?
  6. How do you run three independent async calls in parallel?
  7. What does async () => 5 return when called?
  8. Why can return promise inside try differ from return await promise?
  9. What is the most common cause of flaky async tests?
  10. In a CommonJS .js file, how do you use await at the top?

💼 Interview Questions and Answers

Q1. What do async and await do?

async makes a function always return a promise: return values fulfil it and thrown errors reject it. await pauses that async function until a promise settles, then either returns the value or throws the rejection reason. It is syntax over promises and the event loop: the pause is non-blocking, and code after await resumes as a microtask.

Q2. How do you handle errors with async/await?

Wrap awaits in try...catch (with finally for cleanup), or call .catch() on the promise returned by the async function. Errors from several awaited steps can share one try. Let errors propagate when the caller (for example a test runner) should handle them, and use return await inside a try when the local catch must see the rejection.

Q3. What is wrong with using await inside forEach?

forEach calls the callback for every item and ignores its return value, so the promises from an async callback are never awaited. The surrounding function continues immediately, the work finishes later (or not before the test ends), and errors become unhandled rejections. Use for...of with await for sequential processing or await Promise.all(items.map(...)) for parallel processing.

Q4. Predict the output.

📄 predict.js

async function a() {
  console.log("a1");
  await b();
  console.log("a2");
}
async function b() {
  console.log("b");
}
console.log("start");
a();
console.log("end");

⌨️ Terminal

node predict.js

🖥️ Output

start
a1
b
end
a2

The async function runs synchronously until its first await: “start”, “a1”, “b” (b runs immediately when called), then “end” from the synchronous code, and finally “a2” as a microtask after the awaited promise settles.


❓ Frequently Asked Questions

🤔 Is async/await better than promises?

It is built on promises. For sequential logic and error handling it is clearer; combine it with Promise.all and friends for parallel work.

🤔 Can I use await without async?

Only at the top level of an ES module. Inside any function, the function must be declared async.

🤔 Does await make code slower?

No measurable overhead in practice. What makes code slow is awaiting independent work one at a time instead of in parallel.

🤔 Why does every Playwright line start with await?

Each browser action (goto, click, fill) and each web-first assertion returns a promise that completes when the browser has done the work. Awaiting keeps the steps in order and makes failures appear in the right test.


🏁 Summary

  • async functions always return promises; await pauses only the current async function.
  • Rejections make await throw, so use try...catch...finally for error handling and cleanup.
  • Await dependent steps one by one, and independent work together with Promise.all.
  • Use for...of or Promise.all(map) in loops, never forEach with async callbacks.
  • Top-level await works in ES modules; a missing await is the most common cause of flaky tests.

Next, continue with Lesson 51: Fetch API. For extra practice, solve the JavaScript async/await practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in