JavaScript Exception Handling: try, catch, finally and throw

Things go wrong in every real program: a server returns 500, a JSON file is malformed, an element never appears. Exception handling decides what happens next: retry, report a clear message, clean up, or stop. For testers it matters twice, because a test fails by throwing an error. In this lesson you will learn how try, catch, finally and throw work, what is inside an error object, the built-in error types and their real messages, and the habits that make failures easy to diagnose.

📖 What You’ll Learn: errors and exceptions, try…catch, the error object (name, message, stack, cause), built-in error types with real messages, throw and why to throw Error objects, catching selectively and rethrowing, finally and cleanup, optional catch binding, wrapping errors with cause, errors in async code, unhandled errors, and how assertion failures work in tests.


💥 What Is an Exception?

Definition: an exception is an error that is thrown while the program runs. It stops the current code immediately and travels up the call stack until some code catches it. If nothing catches it, Node.js prints the error and exits (in a browser, it is reported in the console).

📄 uncaught.js

function parsePrice(text) {
  const value = Number(text);
  if (Number.isNaN(value)) {
    throw new Error(`Not a price: "${text}"`);
  }
  return value;
}

console.log(parsePrice("499"));
console.log(parsePrice("free"));      // throws: nothing below this line runs
console.log("never printed");

⌨️ Terminal

node uncaught.js

🖥️ Output

499
/home/you/js-course/uncaught.js:4
    throw new Error(`Not a price: "${text}"`);
    ^

Error: Not a price: "free"
    at parsePrice (/home/you/js-course/uncaught.js:4:11)
    at Object.<anonymous> (/home/you/js-course/uncaught.js:10:13)

Node.js v26.13.0

The output shows the error type and message, then the stack trace: the chain of function calls that led to the error, with file names and line numbers. Read it from the top.


🛡️ try…catch

Wrap code that might fail in try { ... }. If an error is thrown inside, JavaScript jumps straight to catch (error) { ... }, and the program continues after the block.

📄 try-catch.js

function parsePrice(text) {
  const value = Number(text);
  if (Number.isNaN(value)) throw new Error(`Not a price: "${text}"`);
  return value;
}

for (const input of ["499", "free", "12.5"]) {
  try {
    const price = parsePrice(input);
    console.log("parsed:", price);
  } catch (error) {
    console.log("skipped:", error.message);
  }
}
console.log("loop finished");

⌨️ Terminal

node try-catch.js

🖥️ Output

parsed: 499
skipped: Not a price: "free"
parsed: 12.5
loop finished
  • Code in try after the failing line is skipped.
  • catch runs only if something was thrown; otherwise it is skipped.
  • The error variable exists only inside the catch block.

⚠️ Watch out: try...catch only catches errors thrown while the code inside it runs. It cannot catch a SyntaxError in the same file (the file never starts) or an error thrown later by a callback, such as inside setTimeout.


🔍 The Error Object

Errors are objects. The most useful properties are:

PropertyContains
nameThe error type, such as "TypeError"
messageA human-readable description
stackThe name, message and call stack as text (non-standard but available in all engines)
causeThe original error that caused this one (ES2022)

📄 error-object.js

function loadUser() {
  const response = undefined;      // pretend the API returned nothing
  return response.data;            // TypeError
}

try {
  loadUser();
} catch (err) {
  console.log("name:   ", err.name);
  console.log("message:", err.message);
  console.log("is Error?", err instanceof Error, err instanceof TypeError);
  console.log("stack, first 2 lines:\n" + err.stack.split("\n").slice(0, 2).join("\n"));
}

⌨️ Terminal

node error-object.js

🖥️ Output

name:    TypeError
message: Cannot read properties of undefined (reading 'data')
is Error? true true
stack, first 2 lines:
TypeError: Cannot read properties of undefined (reading 'data')
    at loadUser (/home/you/js-course/error-object.js:3:19)

📚 Built-in Error Types

JavaScript throws different error types for different problems. Recognising them speeds up debugging:

📄 types.js

const cases = {
  ReferenceError: () => notDefinedVariable,
  TypeError: () => null.length,
  RangeError: () => new Array(-1),
  SyntaxError: () => JSON.parse("{bad json}"),
  URIError: () => decodeURIComponent("%"),
};

for (const [expected, fn] of Object.entries(cases)) {
  try {
    fn();
  } catch (e) {
    console.log(`${e.name.padEnd(15)} ${e.message}`);
  }
}

⌨️ Terminal

node types.js

🖥️ Output

ReferenceError  notDefinedVariable is not defined
TypeError       Cannot read properties of null (reading 'length')
RangeError      Invalid array length
SyntaxError     Expected property name or '}' in JSON at position 1 (line 1 column 2)
URIError        URI malformed
TypeUsually meansTypical fix
ReferenceErrorA name is not defined (typo, missing import, used before declaration)Check spelling, imports and declaration order
TypeErrorWrong kind of value: calling a non-function, reading a property of null/undefined, assigning to a constantCheck what the value really is; often a missing await or empty result
RangeErrorA number is out of range, or the call stack overflowedValidate numbers; fix recursion
SyntaxErrorInvalid code, or invalid JSON passed to JSON.parseFix the code or the data
URIErrorMalformed URI in encodeURI/decodeURIValidate the string
AggregateErrorSeveral errors at once (for example Promise.any)Inspect err.errors

🚀 throw: Raising Your Own Errors

throw stops the current function and raises an exception. You can throw any value, but always throw an Error (or a subclass): only Error objects carry a stack trace and work with instanceof and test frameworks.

📄 throw.js

function withdraw(balance, amount) {
  if (typeof amount !== "number") throw new TypeError(`amount must be a number, got ${typeof amount}`);
  if (amount <= 0) throw new RangeError(`amount must be positive, got ${amount}`);
  if (amount > balance) throw new Error(`Insufficient funds: balance ${balance}, requested ${amount}`);
  return balance - amount;
}

for (const amount of [200, "200", -5, 5000]) {
  try {
    console.log("new balance:", withdraw(1000, amount));
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }
}

try {
  throw "something broke";          // a string: works, but no stack, no name
} catch (e) {
  console.log(typeof e, e.stack);
}

⌨️ Terminal

node throw.js

🖥️ Output

new balance: 800
TypeError: amount must be a number, got string
RangeError: amount must be positive, got -5
Error: Insufficient funds: balance 1000, requested 5000
string undefined

💡 Tip: Write error messages that answer “what was expected, what happened, and with which input”: Expected status 200 but got 503 for GET /api/orders is far more useful than Request failed.


🎯 Catch Selectively and Rethrow

A catch block receives every error, including bugs you did not expect. Handle only the errors you know how to handle, and rethrow the rest so they are not hidden:

📄 rethrow.js

function readConfig(text) {
  try {
    return JSON.parse(text);
  } catch (e) {
    if (e instanceof SyntaxError) {
      console.log("config is not valid JSON, using defaults");
      return { retries: 0 };
    }
    throw e;                          // anything else is a real bug: let it propagate
  }
}

console.log(readConfig('{"retries": 2}'));
console.log(readConfig("{retries: 2}"));

⌨️ Terminal

node rethrow.js

🖥️ Output

{ retries: 2 }
config is not valid JSON, using defaults
{ retries: 0 }

⚠️ Watch out: An empty catch {} that swallows every error is one of the worst bugs in test code: the test keeps going with bad data, or passes while the feature is broken. At minimum, log the error; usually, rethrow it.


🧹 finally: Always Clean Up

A finally block runs after try and catch, whether or not an error happened, and even if the code returns early. Use it for cleanup: closing files, connections or browsers, stopping timers, deleting test data.

📄 finally.js

function runStep(name, shouldFail) {
  console.log(`open connection for ${name}`);
  try {
    if (shouldFail) throw new Error(`${name} failed`);
    return `${name} ok`;
  } catch (e) {
    console.log("caught:", e.message);
    return `${name} handled`;
  } finally {
    console.log(`close connection for ${name}`);   // always runs
  }
}

console.log(runStep("login", false));
console.log(runStep("payment", true));

⌨️ Terminal

node finally.js

🖥️ Output

open connection for login
close connection for login
login ok
open connection for payment
caught: payment failed
close connection for payment
payment handled

try...finally without a catch is also valid: the cleanup runs and the error still propagates to the caller, which is exactly what a test helper usually wants.

📄 try-finally.js

function withTempFile(action) {
  console.log("create temp file");
  try {
    return action();
  } finally {
    console.log("delete temp file");
  }
}

try {
  withTempFile(() => { throw new Error("upload failed"); });
} catch (e) {
  console.log("caller sees:", e.message);
}

⌨️ Terminal

node try-finally.js

🖥️ Output

create temp file
delete temp file
caller sees: upload failed

If you do not need the error object, you can omit it: try { ... } catch { ... } (optional catch binding, ES2019).


🔗 Wrapping Errors with cause

When you catch a low-level error and throw a more meaningful one, attach the original as cause (ES2022). The new message explains the context; the cause keeps the technical detail:

📄 cause.js

function loadTestData(json, file) {
  try {
    return JSON.parse(json);
  } catch (e) {
    throw new Error(`Could not load test data from ${file}`, { cause: e });
  }
}

try {
  loadTestData("{users: []}", "users.json");
} catch (e) {
  console.log(e.message);
  console.log("caused by:", e.cause.name, "-", e.cause.message);
}

⌨️ Terminal

node cause.js

🖥️ Output

Could not load test data from users.json
caused by: SyntaxError - Expected property name or '}' in JSON at position 1 (line 1 column 2)

⏳ Errors in Asynchronous Code

With async/await, try...catch works across await just like synchronous code. But an error thrown inside a callback that runs later cannot be caught by a try that has already finished:

📄 async-errors.js

const fetchOrder = async (id) => {
  await new Promise((r) => setTimeout(r, 5));
  if (id < 0) throw new Error(`Order ${id} not found`);
  return { id };
};

async function main() {
  try {
    console.log(await fetchOrder(7));
    console.log(await fetchOrder(-1));
  } catch (e) {
    console.log("caught async error:", e.message);
  }

  try {
    setTimeout(() => {
      try {
        throw new Error("thrown later in a callback");
      } catch (e) {
        console.log("must be caught inside the callback:", e.message);
      }
    }, 0);
  } catch {
    console.log("never reached");
  }
}
main();

⌨️ Terminal

node async-errors.js

🖥️ Output

{ id: 7 }
caught async error: Order -1 not found
must be caught inside the callback: thrown later in a callback

⚠️ Watch out: Forgetting await is the most common async error bug: try { saveOrder(); } catch {} does not catch a rejection from an async saveOrder, because the promise rejects after the try has ended. Node.js then reports an unhandled promise rejection and exits. Module 10 covers promises in depth.


🧪 Tester Scenario: How a Test Fails

Assertions are just functions that throw when a check fails. A test runner calls each test inside try...catch: no error means passed, an error means failed, and the error’s message becomes the failure report. This is why a swallowed error makes a test pass wrongly.

📄 test-fail.js

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

function runTest(name, fn) {
  try {
    fn();
    console.log(`✓ ${name}`);
  } catch (e) {
    console.log(`✗ ${name}\n    ${e.name}: ${e.message.split("\n").filter(Boolean).slice(0, 2).join(" ")}`);
  }
}

const response = { status: 503, body: { items: [] } };

runTest("status is 200", () => assert.equal(response.status, 200));
runTest("items is an array", () => assert.ok(Array.isArray(response.body.items)));
runTest("swallowed error hides the bug", () => {
  try {
    assert.equal(response.status, 200);
  } catch {
    // nothing here: the failure disappears
  }
});

⌨️ Terminal

node test-fail.js

🖥️ Output

✗ status is 200
    AssertionError: Expected values to be strictly equal: 503 !== 200
✓ items is an array
✓ swallowed error hides the bug

The third “test” passes even though the status is wrong, because its catch swallowed the assertion error. Never wrap assertions in try...catch unless you rethrow.


📝 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 safeDivide(a, b) that throws a RangeError when b is 0. Call it for (10, 2) and (10, 0) and print the result or the error message.

Show answer

📄 practice1.js

function safeDivide(a, b) {
  if (b === 0) throw new RangeError("Division by zero");
  return a / b;
}
for (const [a, b] of [[10, 2], [10, 0]]) {
  try {
    console.log(safeDivide(a, b));
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }
}

🖥️ Output

5
RangeError: Division by zero

Q2. Parse each string in ['{"a":1}', "not json", '[1,2]'] with JSON.parse, printing the parsed value or invalid.

Show answer

📄 practice2.js

for (const text of ['{"a":1}', "not json", "[1,2]"]) {
  try {
    console.log(JSON.parse(text));
  } catch {
    console.log("invalid:", text);
  }
}

🖥️ Output

{ a: 1 }
invalid: not json
[ 1, 2 ]

Q3. Predict the order of the printed lines, then run it.

function f() {
  try {
    console.log("try");
    return "returned";
  } finally {
    console.log("finally");
  }
}
console.log(f());
Show answer

📄 practice3.js

function f() {
  try {
    console.log("try");
    return "returned";
  } finally {
    console.log("finally");
  }
}
console.log(f());

🖥️ Output

try
finally
returned

finally runs before the function actually returns, so “finally” is printed before the returned value is logged.

Q4. Write getAge(user) that throws a TypeError if user is not an object and an Error if age is missing. Test it with null, {} and { age: 30 }.

Show answer

📄 practice4.js

function getAge(user) {
  if (typeof user !== "object" || user === null) throw new TypeError("user must be an object");
  if (!("age" in user)) throw new Error("user.age is missing");
  return user.age;
}
for (const u of [null, {}, { age: 30 }]) {
  try { console.log(getAge(u)); } catch (e) { console.log(`${e.name}: ${e.message}`); }
}

🖥️ Output

TypeError: user must be an object
Error: user.age is missing
30

Q5. Wrap a failing JSON.parse in a new error "Bad API response" with the original error as cause, then print both messages.

Show answer

📄 practice5.js

try {
  try {
    JSON.parse("<html>502</html>");
  } catch (e) {
    throw new Error("Bad API response", { cause: e });
  }
} catch (e) {
  console.log(e.message, "|", e.cause.message);
}

🖥️ Output

Bad API response | Unexpected token '<', "<html>502</html>" is not valid JSON

Q6. Fix this helper so the error is not swallowed: it should log a message and then let the error reach the caller.

function clickSave(save) {
  try {
    save();
  } catch (e) {
  }
}
Show answer

📄 practice6.js

function clickSave(save) {
  try {
    save();
  } catch (e) {
    console.log("clickSave failed:", e.message);
    throw e;
  }
}
try {
  clickSave(() => { throw new Error("Save button disabled"); });
} catch (e) {
  console.log("caller sees:", e.message);
}

🖥️ Output

clickSave failed: Save button disabled
caller sees: Save button disabled

🧠 MCQ Quiz: Exception Handling

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 happens to the remaining code in a try block after an error is thrown?
  2. When does a finally block run?
  3. What does null.length throw?
  4. What does using an undeclared variable throw?
  5. What does JSON.parse("{bad}") throw?
  6. Why should you throw Error objects instead of strings?
  7. What is the purpose of throw e; inside catch?
  8. What does the cause option do?
  9. Can try/catch catch an error thrown later inside setTimeout’s callback?
  10. Why does a test pass when its assertion is wrapped in an empty catch?

💼 Interview Questions and Answers

Q1. Explain try, catch and finally.

try contains code that may throw. If something throws, control jumps to catch, which receives the error. finally runs afterwards in every case (success, caught error, or even a return inside try/catch) and is used for cleanup. You can use try...catch, try...finally or all three.

Q2. What is the difference between TypeError, ReferenceError and SyntaxError?

ReferenceError: a variable name cannot be found (typo, missing import, temporal dead zone). TypeError: an operation is used on the wrong kind of value, such as calling something that is not a function or reading a property of undefined. SyntaxError: the code (or JSON) cannot be parsed at all; for code it is raised before the file runs.

Q3. What does finally return if both try and finally have return statements?

📄 finally-return.js

function f() {
  try {
    return "from try";
  } finally {
    return "from finally";
  }
}
console.log(f());

⌨️ Terminal

node finally-return.js

🖥️ Output

from finally

The finally return wins and silently replaces the try’s value (or even a thrown error). That is why returning from finally is considered bad practice; ESLint’s no-unsafe-finally rule reports it.

Q4. How should errors be handled in test automation code?

  • Let assertion errors propagate so the test fails with a clear message; never swallow them.
  • Catch only expected, recoverable errors (for example a known flaky third-party call) and rethrow everything else.
  • Add context when rethrowing (new Error("Login failed for user X", { cause })).
  • Use finally or framework hooks for cleanup (delete test data, close resources).
  • Always await async calls inside try so rejections are caught.

❓ Frequently Asked Questions

🤔 Should I wrap all my code in try/catch?

No. Catch errors only where you can do something useful: recover, add context, or clean up. Elsewhere let them propagate so they are reported with a full stack trace.

🤔 What is the difference between an error and an exception?

In JavaScript the terms are used almost interchangeably: an Error object describes the problem, and throwing it creates an exception that unwinds the call stack.

🤔 Can catch handle only one error type?

JavaScript has no typed catch clauses. Catch everything, check with instanceof or error.name, handle the types you expect, and rethrow the rest.

🤔 How do I see the full stack trace?

Print error.stack, or let the error go uncaught so Node.js prints it. For async code, run Node.js with the default async stack traces and use await consistently.


🏁 Summary

  • Exceptions stop the current code and travel up the call stack until caught; uncaught errors stop the program.
  • try...catch handles errors; finally always runs and is used for cleanup.
  • Error objects have name, message, stack and optional cause; learn the built-in types.
  • Throw Error objects with clear messages; catch selectively and rethrow what you cannot handle.
  • Assertions fail tests by throwing, so never swallow errors in test code; await async calls inside try.

Next, continue with Lesson 44: Custom Errors. For extra practice, solve the JavaScript exception handling practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Objects: Properties, Methods, Nested Objects and Copying

Objects are how JavaScript represents things: a user, an order, an API response, a page configuration, a test result. Almost every value you work with in testing, from response.json() to Playwright’s config file, is an object. In this lesson you will learn how to create objects, read and change their properties, add methods, work with nested data, loop through properties, and copy and compare objects without the reference bugs that catch so many beginners.

📖 What You’ll Learn: what an object is, object literals, reading properties with dot and bracket notation, adding, updating and deleting properties, shorthand properties and computed keys, methods, nested objects, checking whether a property exists, looping over keys and values, objects as references, copying and comparing objects, and objects versus arrays.


🧱 What Is an Object?

Definition: an object is a collection of properties, where each property is a key (a name) paired with a value. Values can be anything: strings, numbers, arrays, functions, even other objects. The usual way to create one is an object literal in curly braces.

📄 object.js

const user = {
  id: 7,
  name: "Asha Rao",
  email: "asha@sqatools.in",
  active: true,
  roles: ["tester", "admin"],
};

console.log(user);
console.log(typeof user, Array.isArray(user));
console.log(Object.keys(user).length, "properties");

⌨️ Terminal

node object.js

🖥️ Output

{
  id: 7,
  name: 'Asha Rao',
  email: 'asha@sqatools.in',
  active: true,
  roles: [ 'tester', 'admin' ]
}
object false
5 properties
  • Each property is written key: value, separated by commas. A trailing comma is allowed.
  • Keys are strings (or symbols). Quotes are optional when the key is a valid identifier: name and "name" are the same key.
  • Use objects for one record with named fields, and arrays for an ordered list of similar items.

🔑 Reading Properties: Dot vs Bracket Notation

📄 access.js

const order = { id: 501, "order-status": "shipped", total: 1299, 2026: "year key" };

console.log(order.id);                 // dot notation
console.log(order["total"]);           // bracket notation with a string
console.log(order["order-status"]);    // needed: the key contains a dash
console.log(order[2026]);              // numeric keys are converted to strings

const field = "total";
console.log(order[field]);             // needed: the key is in a variable
console.log(order.field);              // looks for a key literally called "field"
console.log(order.discount);           // missing property: undefined

⌨️ Terminal

node access.js

🖥️ Output

501
1299
shipped
year key
1299
undefined
undefined
UseWhen
obj.keyThe key is a fixed, valid identifier (most of the time)
obj["some-key"]The key has spaces, dashes or starts with a digit
obj[variable]The key is computed or stored in a variable

⚠️ Watch out: Reading a missing property gives undefined, but reading a property of that undefined throws TypeError: Cannot read properties of undefined. Use optional chaining (order.customer?.name) for data that may be missing; see the Optional Chaining lesson.


✏️ Adding, Updating and Deleting Properties

📄 modify.js

const config = { browser: "chromium" };

config.headless = true;          // add
config["retries"] = 2;           // add with brackets
config.browser = "firefox";      // update
delete config.retries;           // remove
console.log(config);

const settings = Object.freeze({ env: "qa" });
settings.env = "prod";           // ignored (throws in strict mode)
console.log(settings.env);

⌨️ Terminal

node modify.js

🖥️ Output

{ browser: 'firefox', headless: true }
qa

Objects declared with const can still be changed, because const only prevents assigning a new object to the variable. Object.freeze (next lesson) makes the object itself read-only.


✂️ Shorthand Properties and Computed Keys

When a variable has the same name as the key, you can write it once (shorthand property). Square brackets around a key let you compute its name from an expression:

📄 shorthand.js

const name = "Asha";
const role = "tester";

const longForm = { name: name, role: role };
const shortForm = { name, role };             // shorthand
console.log(longForm, shortForm);

const env = "qa";
const urls = {
  [`${env}URL`]: "https://qa.example.com",    // computed key
  [`${env}_timeout`]: 15000,
};
console.log(urls);

function pick(obj, key) {
  return { [key]: obj[key] };
}
console.log(pick({ a: 1, b: 2 }, "b"));

⌨️ Terminal

node shorthand.js

🖥️ Output

{ name: 'Asha', role: 'tester' } { name: 'Asha', role: 'tester' }
{ qaURL: 'https://qa.example.com', qa_timeout: 15000 }
{ b: 2 }

🛠️ Methods: Functions Inside Objects

Definition: a method is a property whose value is a function. Inside a method, this refers to the object the method was called on (see the this lesson).

📄 methods.js

const cart = {
  items: [],
  add(name, price, qty = 1) {           // method shorthand
    this.items.push({ name, price, qty });
    return this;                         // return this to allow chaining
  },
  total() {
    return this.items.reduce((sum, i) => sum + i.price * i.qty, 0);
  },
  summary() {
    return `${this.items.length} lines, total ₹${this.total()}`;
  },
};

cart.add("Pen", 10, 3).add("Notebook", 45);
console.log(cart.summary());
console.log(typeof cart.add);

⌨️ Terminal

node methods.js

🖥️ Output

2 lines, total ₹75
function

Returning this from a method allows chaining calls, a style you will meet in builders and in page-object methods.


🪆 Nested Objects

Real data is nested: an order has a customer, the customer has an address, the order has a list of items. Chain dots and brackets to reach inner values:

📄 nested.js

const order = {
  id: 501,
  customer: {
    name: "Asha",
    address: { city: "Pune", pin: "411001" },
  },
  items: [
    { sku: "PEN-1", price: 10, qty: 3 },
    { sku: "BOOK-9", price: 45, qty: 1 },
  ],
};

console.log(order.customer.address.city);
console.log(order.items[1].sku);
console.log(order.items.length);
console.log(order.customer.phone?.mobile ?? "no phone");

order.customer.address.city = "Mumbai";    // change a nested value
console.log(order.customer.address);

⌨️ Terminal

node nested.js

🖥️ Output

Pune
BOOK-9
2
no phone
{ city: 'Mumbai', pin: '411001' }

💡 Tip: When an API response is deeply nested, destructure the parts you need once (const { customer: { address } } = order;) instead of repeating long chains in every assertion.


🔍 Checking Whether a Property Exists

A property can exist and still hold undefined, so “is the value undefined?” and “does the key exist?” are different questions:

📄 exists.js

const user = { name: "Asha", nickname: undefined };

console.log(user.nickname === undefined, user.age === undefined);   // both true
console.log("nickname" in user, "age" in user);                    // key exists?
console.log(Object.hasOwn(user, "nickname"), Object.hasOwn(user, "toString"));
console.log("toString" in user);                                   // in also sees inherited keys

⌨️ Terminal

node exists.js

🖥️ Output

true true
true false
true false
true
CheckTrue when
obj.key !== undefinedThe key exists with a value other than undefined
"key" in objThe key exists on the object or its prototype chain
Object.hasOwn(obj, "key")The key exists on the object itself (ES2022)

🔁 Looping Through an Object

📄 loop.js

const scores = { asha: 91, ravi: 78, meera: 85 };

for (const name in scores) {
  console.log(name, scores[name]);
}

console.log(Object.keys(scores));
console.log(Object.values(scores));
console.log(Object.entries(scores));

for (const [name, score] of Object.entries(scores)) {
  console.log(`${name.padEnd(6)} ${score >= 80 ? "pass" : "fail"}`);
}

const average = Object.values(scores).reduce((a, b) => a + b, 0) / Object.keys(scores).length;
console.log("average", average.toFixed(1));

⌨️ Terminal

node loop.js

🖥️ Output

asha 91
ravi 78
meera 85
[ 'asha', 'ravi', 'meera' ]
[ 91, 78, 85 ]
[ [ 'asha', 91 ], [ 'ravi', 78 ], [ 'meera', 85 ] ]
asha   pass
ravi   fail
meera  pass
average 84.7

Object.entries combined with for...of and destructuring is the most common way to walk an object. String keys come back in insertion order (integer-like keys come first, in ascending order).


🔗 Objects Are References: Copying and Comparing

Assigning an object to another variable copies the reference, so both names point to the same object. Comparing two objects with === checks whether they are the same object, not whether they have the same contents.

📄 reference.js

const base = { env: "qa", retries: 0 };
const alias = base;
alias.retries = 3;
console.log(base.retries, alias === base);

const copy = { ...base };              // shallow copy
copy.retries = 5;
console.log(base.retries, copy.retries);

console.log({ id: 1 } === { id: 1 });   // different objects
const { isDeepStrictEqual } = require("node:util");
console.log(isDeepStrictEqual({ id: 1, tags: ["a"] }, { id: 1, tags: ["a"] }));

⌨️ Terminal

node reference.js

🖥️ Output

3 true
3 5
false
true

Spread and Object.assign make shallow copies: nested objects are still shared. The Destructuring and Spread lesson and the JSON lesson cover deep copies with structuredClone.


🧪 Tester Scenario: Build and Validate an API Payload

API tests constantly build request bodies and check response objects. This example builds a payload with methods and validates a response against expected fields:

📄 payload.js

const payloadBuilder = {
  data: { name: "Test User", role: "tester", active: true },
  with(key, value) {
    this.data = { ...this.data, [key]: value };
    return this;
  },
  build() {
    return { ...this.data, createdAt: "2026-11-23T10:00:00Z" };
  },
};

const payload = payloadBuilder.with("role", "admin").with("email", "admin@sqatools.in").build();
console.log(payload);

const response = { id: 9001, ...payload, active: "true" };   // simulated server response

const expected = { role: "admin", email: "admin@sqatools.in", active: true };
for (const [key, value] of Object.entries(expected)) {
  const ok = Object.is(response[key], value);
  console.log(`${ok ? "PASS" : "FAIL"} ${key}: expected ${JSON.stringify(value)}, got ${JSON.stringify(response[key])}`);
}
console.log("has id:", Object.hasOwn(response, "id") && typeof response.id === "number");

⌨️ Terminal

node payload.js

🖥️ Output

{
  name: 'Test User',
  role: 'admin',
  active: true,
  email: 'admin@sqatools.in',
  createdAt: '2026-11-23T10:00:00Z'
}
PASS role: expected "admin", got "admin"
PASS email: expected "admin@sqatools.in", got "admin@sqatools.in"
FAIL active: expected true, got "true"
has id: true

The check catches a classic API bug: active came back as the string "true" instead of the boolean true. Playwright’s expect(body).toMatchObject(expected) does this comparison for you.


📝 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. Create a book object with title, author, year and tags (an array). Print the title and the number of tags.

Show answer

📄 practice1.js

const book = { title: "Clean Code", author: "Robert C. Martin", year: 2008, tags: ["craft", "quality"] };
console.log(book.title, book.tags.length);

🖥️ Output

Clean Code 2

Q2. Given const field = "price", read that property from { name: "Lamp", price: 899 }, then add a "discount-code" property with the value "SAVE10".

Show answer

📄 practice2.js

const product = { name: "Lamp", price: 899 };
const field = "price";
console.log(product[field]);
product["discount-code"] = "SAVE10";
console.log(product);

🖥️ Output

899
{ name: 'Lamp', price: 899, 'discount-code': 'SAVE10' }

Q3. Write a counter object with a count property and methods increment(), reset() and value().

Show answer

📄 practice3.js

const counter = {
  count: 0,
  increment() { this.count++; return this; },
  reset() { this.count = 0; return this; },
  value() { return this.count; },
};
counter.increment().increment().increment();
console.log(counter.value());
console.log(counter.reset().value());

🖥️ Output

3
0

Q4. Count how many properties of { a: 1, b: null, c: 0, d: "x", e: undefined } have a value that is not null or undefined.

Show answer

📄 practice4.js

const obj = { a: 1, b: null, c: 0, d: "x", e: undefined };
const count = Object.values(obj).filter((v) => v != null).length;
console.log(count);

🖥️ Output

3

Q5. Print every key: value pair of { env: "qa", browser: "firefox", workers: 4 } in the format ENV=qa.

Show answer

📄 practice5.js

const config = { env: "qa", browser: "firefox", workers: 4 };
for (const [key, value] of Object.entries(config)) {
  console.log(`${key.toUpperCase()}=${value}`);
}

🖥️ Output

ENV=qa
BROWSER=firefox
WORKERS=4

Q6. Make a copy of { name: "Asha", settings: { theme: "dark" } }, change the copy’s theme to "light", and show that the original still says "dark".

Show answer

📄 practice6.js

const original = { name: "Asha", settings: { theme: "dark" } };
const copy = { ...original, settings: { ...original.settings } };
copy.settings.theme = "light";
console.log(original.settings.theme, copy.settings.theme);

🖥️ Output

dark light

Spreading only the outer object would share settings, so the nested object must be spread too (or use structuredClone).


🧠 MCQ Quiz: Objects

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 do you read a property whose name is stored in a variable key?
  2. What does reading a missing property return?
  3. Which is required for the key "order-id"?
  4. What does { name } mean when a variable name exists?
  5. What does delete obj.key do?
  6. What is { a: 1 } === { a: 1 }?
  7. Which check returns true only for the object’s own property, not inherited ones?
  8. What does Object.entries({ a: 1, b: 2 }) return?
  9. Inside a method called as cart.total(), what is this?
  10. Why can you change properties of an object declared with const?

💼 Interview Questions and Answers

Q1. What is the difference between dot notation and bracket notation?

Dot notation (obj.name) is shorter and used when the key is a fixed, valid identifier. Bracket notation (obj["name"]) accepts any string or expression, so it is required for keys with spaces or dashes, keys starting with digits, and dynamic keys stored in variables. Both read the same property.

Q2. How do you check if an object has a property?

Object.hasOwn(obj, key) (or the older obj.hasOwnProperty(key)) checks own properties only. key in obj also checks the prototype chain. Comparing obj[key] !== undefined fails when the property exists but holds undefined. For API assertions, hasOwn is the precise check.

Q3. How do you loop through an object’s properties?

Use Object.keys, Object.values or Object.entries with for...of, for example for (const [key, value] of Object.entries(obj)). for...in also works but includes inherited enumerable properties. Plain objects are not iterable, so for (const x of obj) throws a TypeError.

Q4. Predict the output.

📄 predict.js

const a = { x: 1 };
const b = a;
const c = { ...a };
b.x = 2;
c.x = 3;
console.log(a.x, b.x, c.x, a === b, a === c);

⌨️ Terminal

node predict.js

🖥️ Output

2 2 3 true false

b is the same object as a, so setting b.x changes a.x to 2. c is a separate copy, so its change to 3 does not affect a.


❓ Frequently Asked Questions

🤔 How do I create an empty object?

Use {}. new Object() works too but is never needed. Object.create(null) creates an object with no prototype, useful for pure dictionaries.

🤔 Can object keys be numbers?

Keys are always strings or symbols. A numeric key such as obj[1] is converted to the string “1”. Use a Map if you need keys of any type.

🤔 How do I get the number of properties in an object?

Use Object.keys(obj).length. Objects have no length property.

🤔 What is the difference between an object and JSON?

An object is a value in your program. JSON is a text format for data. JSON.stringify converts an object to JSON text and JSON.parse converts JSON text back to an object.


🏁 Summary

  • Objects store named properties: create them with { key: value } literals.
  • Use dot notation for fixed keys and bracket notation for dynamic or unusual keys.
  • Add, update and delete properties freely; methods are functions stored as properties and use this.
  • Check keys with Object.hasOwn or in, and loop with Object.entries and for...of.
  • Objects are references: copy with spread (shallow) or structuredClone (deep), and compare contents with deep equality.

Next, continue with Lesson 34: Object Methods. For extra practice, solve the JavaScript object practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Array Methods: Complete Guide (Mutating vs Non-Mutating)

JavaScript arrays have more than 30 built-in methods. The single most important thing to know about each one is whether it changes the original array (mutates it) or returns a new one. Getting that wrong causes some of the most confusing bugs in test code, such as shared test data that silently changes between tests. In this lesson you will learn the essential array methods grouped by what they do, with the modern non-mutating versions added in ES2023.

📖 What You’ll Learn: mutating versus non-mutating methods, splice for inserting, removing and replacing, slice for copying parts, concat and spread, join and toString, includes, indexOf and lastIndexOf, reverse and toReversed, fill, flat and flatMap, toSorted, toSpliced and with, Array.isArray, Array.from and Array.of, and a cheat sheet.


⚠️ Mutating vs Non-Mutating Methods

Definition: a mutating method changes the array it is called on. A non-mutating method leaves the original untouched and returns a new value (often a new array).

Mutating (change the array)Non-mutating (return something new)
push, pop, shift, unshiftslice, concat, join
splicetoSpliced (ES2023)
sorttoSorted (ES2023)
reversetoReversed (ES2023)
fill, copyWithinwith (ES2023)
Assigning arr[i] = xmap, filter, flat, flatMap, includes, indexOf, find…

📄 mutating.js

const original = [3, 1, 2];

const sortedCopy = original.toSorted();   // new array
console.log(original, sortedCopy);

const sameArray = original.sort();         // sorts in place AND returns the same array
console.log(original, sameArray === original);

⌨️ Terminal

node mutating.js

🖥️ Output

[ 3, 1, 2 ] [ 1, 2, 3 ]
[ 1, 2, 3 ] true

⚠️ Watch out: Test data defined once at the top of a file and then sorted, reversed or spliced by one test is changed for every later test. Use the non-mutating versions (or copy first with [...arr]) on shared data.


✂️ splice: Insert, Remove and Replace (Mutating)

arr.splice(start, deleteCount, ...itemsToInsert) changes the array in place and returns the removed items.

📄 splice.js

const steps = ["open", "login", "search", "logout"];

const removed = steps.splice(2, 1);                 // remove 1 item at index 2
console.log(removed, steps);

steps.splice(2, 0, "add to cart", "checkout");      // insert without removing
console.log(steps);

steps.splice(1, 1, "login with SSO");               // replace 1 item
console.log(steps);

steps.splice(-1);                                   // remove from index -1 to the end
console.log(steps);

⌨️ Terminal

node splice.js

🖥️ Output

[ 'search' ] [ 'open', 'login', 'logout' ]
[ 'open', 'login', 'add to cart', 'checkout', 'logout' ]
[ 'open', 'login with SSO', 'add to cart', 'checkout', 'logout' ]
[ 'open', 'login with SSO', 'add to cart', 'checkout' ]

Removing an item by value is a common job: find its index first, and only splice if it was found.

📄 remove-by-value.js

const tags = ["smoke", "flaky", "api"];
const i = tags.indexOf("flaky");
if (i !== -1) tags.splice(i, 1);
console.log(tags);

const j = tags.indexOf("missing");
tags.splice(j, 1);          // bug: j is -1, so this removes the LAST item
console.log(tags);

⌨️ Terminal

node remove-by-value.js

🖥️ Output

[ 'smoke', 'api' ]
[ 'smoke' ]

💡 Tip: arr.toSpliced(start, deleteCount, ...items) (ES2023) does the same as splice but returns a new array and leaves the original alone. To remove by value without mutating, arr.filter((x) => x !== value) is the simplest choice.


📎 slice: Copy Part of an Array (Non-Mutating)

arr.slice(start, end) returns a new array with the items from start up to, but not including, end. Negative indexes count from the end. It works exactly like String.prototype.slice.

📄 slice.js

const runs = ["run1", "run2", "run3", "run4", "run5"];

console.log(runs.slice(1, 3));     // index 1 and 2
console.log(runs.slice(2));        // from index 2 to the end
console.log(runs.slice(-2));       // last two
console.log(runs.slice());         // full shallow copy
console.log(runs);                 // unchanged

⌨️ Terminal

node slice.js

🖥️ Output

[ 'run2', 'run3' ]
[ 'run3', 'run4', 'run5' ]
[ 'run4', 'run5' ]
[ 'run1', 'run2', 'run3', 'run4', 'run5' ]
[ 'run1', 'run2', 'run3', 'run4', 'run5' ]
slice(start, end)splice(start, count, ...items)
Changes the original?NoYes
Second argumentEnd index (exclusive)Number of items to remove
ReturnsA new array of the selected itemsAn array of the removed items

🔗 concat, Spread, join and toString

📄 concat-join.js

const smoke = ["login", "search"];
const regression = ["refund", "export"];

console.log(smoke.concat(regression, ["extra"]));   // new array
console.log([...smoke, ...regression]);             // same with spread

console.log(smoke.join(" > "));                     // array -> string
console.log(smoke.join(""), "|", smoke.toString());
console.log([1, [2, [3]]].join("-"));               // nested arrays are stringified
console.log([null, undefined, 0].join(","));        // null/undefined become empty

⌨️ Terminal

node concat-join.js

🖥️ Output

[ 'login', 'search', 'refund', 'export', 'extra' ]
[ 'login', 'search', 'refund', 'export' ]
login > search
loginsearch | login,search
1-2,3
,,0

🔍 includes, indexOf and lastIndexOf

📄 search.js

const codes = [200, 201, 404, 500, 404];

console.log(codes.includes(404), codes.includes(302));
console.log(codes.indexOf(404), codes.lastIndexOf(404), codes.indexOf(302));
console.log(codes.includes(500, 4));                 // search from index 4

console.log([NaN].includes(NaN), [NaN].indexOf(NaN)); // includes handles NaN
console.log([{ id: 1 }].includes({ id: 1 }));        // objects compare by reference

⌨️ Terminal

node search.js

🖥️ Output

true false
2 4 -1
false
true -1
false
  • includes answers “is it there?” and returns a boolean; it also finds NaN.
  • indexOf returns the position or -1; use it when you need the index.
  • Both use strict equality, so they cannot find an object by its contents. Use find/some with a callback for that (lesson 30).

🔃 reverse, toReversed, fill and with

📄 reverse-fill.js

const order = ["first", "second", "third"];

console.log(order.toReversed(), order);   // new reversed array, original kept
order.reverse();                           // in place
console.log(order);

console.log(new Array(4).fill("pending"));
const grid = [0, 0, 0, 0, 0];
grid.fill(1, 1, 3);                        // fill indexes 1 and 2
console.log(grid);

const statuses = ["ok", "ok", "ok"];
console.log(statuses.with(1, "fail"), statuses);   // replace one item in a copy

⌨️ Terminal

node reverse-fill.js

🖥️ Output

[ 'third', 'second', 'first' ] [ 'first', 'second', 'third' ]
[ 'third', 'second', 'first' ]
[ 'pending', 'pending', 'pending', 'pending' ]
[ 0, 1, 1, 0, 0 ]
[ 'ok', 'fail', 'ok' ] [ 'ok', 'ok', 'ok' ]

⚠️ Watch out: Never fill an array with the same object if you plan to change items: new Array(3).fill({}) puts the same object in every slot. Use Array.from({ length: 3 }, () => ({})) to create separate objects.

📄 fill-trap.js

const shared = new Array(2).fill({ count: 0 });
shared[0].count++;
console.log(shared);

const separate = Array.from({ length: 2 }, () => ({ count: 0 }));
separate[0].count++;
console.log(separate);

⌨️ Terminal

node fill-trap.js

🖥️ Output

[ { count: 1 }, { count: 1 } ]
[ { count: 1 }, { count: 0 } ]

🪜 flat and flatMap

flat(depth = 1) returns a new array with nested arrays merged into it up to the given depth. flatMap(fn) maps each item to an array and flattens the result by one level.

📄 flat.js

const suites = [["login", "logout"], ["cart", ["add", "remove"]]];

console.log(suites.flat());          // one level
console.log(suites.flat(Infinity));  // all levels

const tests = [
  { name: "login", tags: ["smoke", "auth"] },
  { name: "cart", tags: ["regression"] },
];
console.log(tests.flatMap((t) => t.tags));                    // all tags
console.log(tests.flatMap((t) => t.tags.map((tag) => `${t.name}:${tag}`)));
console.log([1, 2, 3].flatMap((n) => (n % 2 ? [n, n] : [])));  // duplicate odd, drop even

⌨️ Terminal

node flat.js

🖥️ Output

[ 'login', 'logout', 'cart', [ 'add', 'remove' ] ]
[ 'login', 'logout', 'cart', 'add', 'remove' ]
[ 'smoke', 'auth', 'regression' ]
[ 'login:smoke', 'login:auth', 'cart:regression' ]
[ 1, 1, 3, 3 ]

🧰 Static Methods: Array.isArray, Array.from, Array.of

📄 static.js

console.log(Array.isArray([]), Array.isArray("abc"), Array.isArray({ length: 0 }));

console.log(Array.from("abc"));                              // iterable -> array
console.log(Array.from({ length: 3 }, (_, i) => `user${i + 1}`));
console.log(Array.from(new Map([["a", 1]])));                // Map -> [[key, value]]
console.log(Array.from([1, 2, 3], (n) => n * 10));           // with a mapping function
console.log(Array.of(5), Array.of(1, 2));

⌨️ Terminal

node static.js

🖥️ Output

true false false
[ 'a', 'b', 'c' ]
[ 'user1', 'user2', 'user3' ]
[ [ 'a', 1 ] ]
[ 10, 20, 30 ]
[ 5 ] [ 1, 2 ]

In Node.js tests you often get iterables (Sets, Maps, matchAll results). Array.from(...) or [...iterable] turns them into arrays so every array method becomes available.


📋 Array Methods Cheat Sheet

GoalMethodMutates?
Add / remove at endpush / popYes
Add / remove at startunshift / shiftYes
Insert / remove / replace in the middlesplice (or toSpliced)Yes (No)
Copy partsliceNo
Join arraysconcat, [...a, ...b]No
Array to textjoinNo
Is the value there? Where?includes, indexOf, lastIndexOfNo
Reversereverse (or toReversed)Yes (No)
Sortsort (or toSorted)Yes (No)
Replace one itemarr[i] = x (or with)Yes (No)
Flatten nested arraysflat, flatMapNo
Transform / select / combinemap, filter, reduce (next lesson)No

🧪 Tester Scenario: Keep Shared Test Data Safe

A test file defines a list of users once. Two “tests” each need a modified version. Mutating methods break the second test; non-mutating methods keep both correct:

📄 shared-data.js

const USERS = ["admin", "editor", "viewer"];

// Bad: mutating the shared array
function testRemoveViewerBad(users) {
  users.splice(users.indexOf("viewer"), 1);
  return users.length === 2;
}
function testHasThreeRoles(users) {
  return users.length === 3;
}

const shared = [...USERS];
console.log("bad:", testRemoveViewerBad(shared), testHasThreeRoles(shared));

// Good: non-mutating versions
function testRemoveViewerGood(users) {
  const withoutViewer = users.filter((u) => u !== "viewer");
  return withoutViewer.length === 2;
}
console.log("good:", testRemoveViewerGood(USERS), testHasThreeRoles(USERS));
console.log("reversed view:", USERS.toReversed(), "original:", USERS);

⌨️ Terminal

node shared-data.js

🖥️ Output

bad: true false
good: true true
reversed view: [ 'viewer', 'editor', 'admin' ] original: [ 'admin', 'editor', 'viewer' ]

💡 Tip: Object.freeze(USERS) makes accidental mutation throw an error in strict mode, which turns this kind of hidden bug into an immediate failure.


📝 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. Remove "b" and "c" from ["a", "b", "c", "d"] with one splice call and print the removed items and the array.

Show answer

📄 practice1.js

const letters = ["a", "b", "c", "d"];
const removed = letters.splice(1, 2);
console.log(removed, letters);

🖥️ Output

[ 'b', 'c' ] [ 'a', 'd' ]

Q2. Insert "verify email" between "register" and "login" in ["register", "login", "logout"] without changing the original array.

Show answer

📄 practice2.js

const steps = ["register", "login", "logout"];
const updated = steps.toSpliced(1, 0, "verify email");
console.log(updated, steps);

🖥️ Output

[ 'register', 'verify email', 'login', 'logout' ] [ 'register', 'login', 'logout' ]

Q3. Get the middle three items of [10, 20, 30, 40, 50] with slice.

Show answer

📄 practice3.js

const values = [10, 20, 30, 40, 50];
console.log(values.slice(1, 4));

🖥️ Output

[ 20, 30, 40 ]

Q4. Turn ["2026", "11", "23"] into the string "2026-11-23" and back into an array.

Show answer

📄 practice4.js

const parts = ["2026", "11", "23"];
const date = parts.join("-");
console.log(date, date.split("-"));

🖥️ Output

2026-11-23 [ '2026', '11', '23' ]

Q5. From [{ suite: "a", tests: ["t1", "t2"] }, { suite: "b", tests: ["t3"] }], produce a flat list of all test names with flatMap.

Show answer

📄 practice5.js

const suites = [{ suite: "a", tests: ["t1", "t2"] }, { suite: "b", tests: ["t3"] }];
console.log(suites.flatMap((s) => s.tests));

🖥️ Output

[ 't1', 't2', 't3' ]

Q6. Write removeValue(arr, value) that returns a new array without any occurrence of value, and leaves the input unchanged.

Show answer

📄 practice6.js

const removeValue = (arr, value) => arr.filter((x) => x !== value);
const tags = ["smoke", "flaky", "api", "flaky"];
console.log(removeValue(tags, "flaky"), tags);

🖥️ Output

[ 'smoke', 'api' ] [ 'smoke', 'flaky', 'api', 'flaky' ]

🧠 MCQ Quiz: Array Methods

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 method does NOT change the original array?
  2. What does splice return?
  3. What is [1, 2, 3, 4].slice(1, 3)?
  4. What does arr.splice(-1, 1) do?
  5. Which ES2023 method sorts without mutating?
  6. What is [[1, 2], [3, [4]]].flat()?
  7. What does [NaN].includes(NaN) return?
  8. What is wrong with new Array(3).fill({})?
  9. What does ["a", "b"].join("") return?
  10. What does [5, 1].sort() === original tell you?

💼 Interview Questions and Answers

Q1. What is the difference between slice and splice?

slice(start, end) is non-mutating: it returns a shallow copy of a portion, with end exclusive. splice(start, deleteCount, ...items) mutates the array: it removes and/or inserts items in place and returns the removed items. Since ES2023, toSpliced provides a non-mutating version of splice.

Q2. Which array methods mutate the original array?

push, pop, shift, unshift, splice, sort, reverse, fill and copyWithin, plus direct assignment (arr[i] = x, arr.length = 0). Everything else, including map, filter, slice, concat, flat and the ES2023 methods toSorted, toReversed, toSpliced and with, returns a new value.

Q3. How do you remove duplicates from an array?

📄 dedupe.js

const tags = ["smoke", "api", "smoke", "ui", "api"];
console.log([...new Set(tags)]);
console.log(tags.filter((t, i) => tags.indexOf(t) === i));

const users = [{ id: 1 }, { id: 2 }, { id: 1 }];
console.log([...new Map(users.map((u) => [u.id, u])).values()]);

⌨️ Terminal

node dedupe.js

🖥️ Output

[ 'smoke', 'api', 'ui' ]
[ 'smoke', 'api', 'ui' ]
[ { id: 1 }, { id: 2 } ]

A Set is simplest for primitives. For objects, deduplicate by a key, for example with a Map keyed by id.

Q4. What is the difference between flat and flatMap?

flat(depth) only flattens nested arrays (default depth 1, Infinity for all levels). flatMap(fn) first maps each element with fn and then flattens the result by exactly one level; it is equivalent to map(fn).flat() but more efficient, and returning an empty array from fn removes the element.


❓ Frequently Asked Questions

🤔 How do I empty an array in JavaScript?

Set arr.length = 0 or call arr.splice(0) to empty the same array, or assign a new empty array (arr = []) if the variable is let and nothing else holds a reference.

🤔 How do I add an item to the start of an array without mutating it?

Use spread: [newItem, ...arr]. To add at the end: [...arr, newItem].

🤔 Are toSorted and toReversed safe to use?

Yes. They are part of ES2023 and supported by Node.js 20+ and all current browsers.

🤔 What is the difference between includes and some?

includes(value) checks for an exact value with strict equality. some(fn) runs a test function, so it can match objects by their properties.


🏁 Summary

  • Know which methods mutate: push/pop/shift/unshift/splice/sort/reverse/fill change the array.
  • splice inserts, removes and replaces in place; slice copies part of an array.
  • concat/spread join arrays; join turns them into text; includes/indexOf search for values.
  • flat and flatMap flatten nested arrays.
  • ES2023 toSorted, toReversed, toSpliced and with return new arrays, ideal for shared test data.

Next, continue with Lesson 30: map, filter and reduce. For extra practice, solve the JavaScript array practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Strings and String Methods: Complete Guide with Examples

Most of what a tester checks is text: page titles, error messages, URLs, table cells, API fields and log lines. JavaScript strings come with dozens of built-in methods to search, cut, clean, change and compare text. In this lesson you will learn how strings work, the methods you will use every day, the difference between similar methods such as slice and substring, and how to clean real UI text before an assertion.

📖 What You’ll Learn: creating strings with quotes and escapes, length and indexing, at(), immutability, searching with includes, startsWith, endsWith and indexOf, extracting with slice and substring, changing case, trim, padStart and padEnd, repeat, replace and replaceAll, split and join, comparing strings with localeCompare, Unicode and emoji length, and cleaning UI text for tests.


🔤 Creating Strings

Definition: a string is a sequence of characters used to represent text. You write string literals with double quotes, single quotes or back-ticks:

📄 create.js

const double = "QA Engineer";
const single = 'Playwright';
const backtick = `Score: ${40 + 2}`;   // template literal, next lesson

console.log(double, "|", single, "|", backtick);
console.log(typeof double, String(123), typeof String(123));

⌨️ Terminal

node create.js

🖥️ Output

QA Engineer | Playwright | Score: 42
string 123 string

Double and single quotes behave the same. Pick one style for your project (Prettier uses double quotes by default). Use the other kind when the text contains a quote, or escape it with a backslash:

📄 escapes.js

console.log("It's ready");
console.log('She said "pass"');
console.log("She said \"pass\"");
console.log("Line 1\nLine 2");      // \n = new line
console.log("Col1\tCol2");          // \t = tab
console.log("C:\\tests\\login.spec.js");   // \\ = one backslash

⌨️ Terminal

node escapes.js

🖥️ Output

It's ready
She said "pass"
She said "pass"
Line 1
Line 2
Col1	Col2
C:\tests\login.spec.js
EscapeMeaning
\nNew line
\tTab
\\Backslash
\" / \'Quote inside a string with the same quotes
\u{1F600}A Unicode character by code point

📏 Length, Indexes and at()

Each character has a position (an index) starting at 0. length is the number of characters.

📄 index.js

const word = "Selenium";

console.log(word.length);
console.log(word[0], word[3], word[word.length - 1]);
console.log(word[20]);            // out of range: undefined
console.log(word.at(0), word.at(-1), word.at(-2));   // at() accepts negative indexes

⌨️ Terminal

node index.js

🖥️ Output

8
S e m
undefined
S m u

💡 Tip: str.at(-1) (ES2022) is the clearest way to read the last character. With bracket notation you need str[str.length - 1].


🔒 Strings Are Immutable

Definition: immutable means a string cannot be changed after it is created. Every string method returns a new string and leaves the original untouched.

📄 immutable.js

let status = "passed";

status.toUpperCase();          // result is thrown away
console.log(status);

status[0] = "P";               // silently ignored
console.log(status);

status = status.toUpperCase(); // store the new string
console.log(status);

⌨️ Terminal

node immutable.js

🖥️ Output

passed
passed
PASSED

⚠️ Watch out: A very common bug is calling a method and not using its result: name.trim(); on its own line does nothing. Write name = name.trim(); or use the result directly.


🔍 Searching: includes, startsWith, endsWith, indexOf

📄 search.js

const url = "https://qa.example.com/checkout?step=2";

console.log(url.includes("checkout"));        // contains?
console.log(url.startsWith("https://"));      // begins with?
console.log(url.endsWith("step=2"));          // ends with?
console.log(url.indexOf("/"), url.lastIndexOf("/"));
console.log(url.indexOf("cart"));             // not found: -1
console.log(url.includes("Checkout"));        // case-sensitive!
console.log(url.toLowerCase().includes("Checkout".toLowerCase()));

⌨️ Terminal

node search.js

🖥️ Output

true
true
true
6 22
-1
false
true
MethodReturns
includes(text)true/false
startsWith(text) / endsWith(text)true/false
indexOf(text) / lastIndexOf(text)Position of the first / last match, or -1
search(regex)Position of the first regex match, or -1

All of these are case-sensitive. Lower-case both sides for a case-insensitive check.


✂️ Extracting: slice and substring

slice(start, end) returns the characters from start up to, but not including, end. Leave out end to go to the end of the string. Negative numbers count from the end.

📄 slice.js

const id = "ORD-2026-000451";

console.log(id.slice(0, 3));     // "ORD"
console.log(id.slice(4, 8));     // "2026"
console.log(id.slice(9));        // from index 9 to the end
console.log(id.slice(-6));       // last 6 characters
console.log(id.slice(-6, -3));

console.log(id.substring(4, 8)); // like slice for positive numbers
console.log(id.substring(8, 4)); // swaps the arguments if start > end
console.log(id.slice(8, 4));     // slice returns ""
console.log(id.substring(-6));   // negative numbers become 0

⌨️ Terminal

node slice.js

🖥️ Output

ORD
2026
000451
000451
000
2026
2026

ORD-2026-000451

💡 Tip: Prefer slice. It supports negative indexes and behaves the same as Array.prototype.slice. The old substr method is deprecated; do not use it in new code.

Combine indexOf and slice to cut text at a marker:

📄 cut.js

const email = "asha.rao@sqatools.in";
const at = email.indexOf("@");
console.log(email.slice(0, at), "|", email.slice(at + 1));

⌨️ Terminal

node cut.js

🖥️ Output

asha.rao | sqatools.in

🧹 Changing Case, Trimming, Padding and Repeating

📄 clean.js

const raw = "   Order CONFIRMED   ";

console.log(JSON.stringify(raw.trim()));
console.log(JSON.stringify(raw.trimStart()), JSON.stringify(raw.trimEnd()));
console.log(raw.trim().toLowerCase(), "|", raw.trim().toUpperCase());

const invoice = "42";
console.log(invoice.padStart(6, "0"));     // "000042"
console.log("Total".padEnd(10, ".") + "₹499");

console.log("=".repeat(20));
console.log("ab".repeat(3));

⌨️ Terminal

node clean.js

🖥️ Output

"Order CONFIRMED"
"Order CONFIRMED   " "   Order CONFIRMED"
order confirmed | ORDER CONFIRMED
000042
Total.....₹499
====================
ababab
  • trim() removes spaces, tabs and line breaks from both ends; text copied from web pages often has them.
  • padStart/padEnd fill a string to a target length, useful for IDs and aligned report columns.
  • toUpperCase/toLowerCase help with case-insensitive comparisons.

🔁 replace and replaceAll

replace(search, replacement) replaces the first match only when search is a string. replaceAll (ES2021) replaces every match.

📄 replace.js

const price = "₹1,29,999";

console.log(price.replace(",", ""));        // only the first comma
console.log(price.replaceAll(",", ""));     // every comma
console.log(price.replace(/[₹,]/g, ""));    // regex with g flag: all matches

const template = "Hello {name}, your order {id} has shipped";
const message = template.replace("{name}", "Asha").replace("{id}", "#451");
console.log(message);

⌨️ Terminal

node replace.js

🖥️ Output

₹129,999
₹129999
129999
Hello Asha, your order #451 has shipped

Regular expressions (lesson 27) make replace far more powerful, for example to remove every non-digit character.


✂️ split and join

split(separator) breaks a string into an array. The array method join(separator) does the reverse.

📄 split-join.js

const csvRow = "asha,tester,Pune,active";
const fields = csvRow.split(",");
console.log(fields, fields.length);

const [name, role] = fields;
console.log(name, role);

console.log("a b  c".split(" "));          // two spaces give an empty item
console.log("a b  c".split(/\s+/));       // regex: any run of whitespace
console.log("QA".split(""));              // into characters
console.log("x,y,z".split(",", 2));        // limit the number of parts

const tags = ["smoke", "login", "p1"];
console.log(tags.join(", "), "|", tags.join("-"));

const slug = "  Learn JavaScript Strings  ".trim().toLowerCase().split(" ").join("-");
console.log(slug);

⌨️ Terminal

node split-join.js

🖥️ Output

[ 'asha', 'tester', 'Pune', 'active' ] 4
asha tester
[ 'a', 'b', '', 'c' ]
[ 'a', 'b', 'c' ]
[ 'Q', 'A' ]
[ 'x', 'y' ]
smoke, login, p1 | smoke-login-p1
learn-javascript-strings

⚖️ Comparing Strings

=== compares exactly, including case and spaces. < and > compare by character codes, so uppercase letters sort before lowercase ones. localeCompare compares the way people expect for a language:

📄 compare.js

console.log("apple" === "Apple");
console.log("Zebra" < "apple");                       // code order: true
console.log("apple".localeCompare("Zebra"));          // negative: apple first

const names = ["ravi", "Asha", "émile", "Bala"];
console.log([...names].sort());                        // code order
console.log([...names].sort((a, b) => a.localeCompare(b)));   // human order

console.log("résumé".localeCompare("RESUME", "en", { sensitivity: "base" }) === 0);

⌨️ Terminal

node compare.js

🖥️ Output

false
true
-1
[ 'Asha', 'Bala', 'ravi', 'émile' ]
[ 'Asha', 'Bala', 'émile', 'ravi' ]
true

💡 Tip: When a test checks that a table column is sorted, build the expected order with localeCompare (or Intl.Collator) in the same locale as the application.


😀 Unicode, Emoji and length

JavaScript strings are made of UTF-16 code units. Most characters use one unit, but many emoji and some rare characters use two, so length can be larger than the number of visible characters:

📄 unicode.js

const text = "QA 👍";
console.log(text.length);                // 5, not 4
console.log([...text].length);           // spread splits by code point: 4
console.log(text.slice(0, 4));           // may cut an emoji in half
console.log([...text].slice(0, 4).join(""));
console.log("👍".codePointAt(0).toString(16));

⌨️ Terminal

node unicode.js

🖥️ Output

5
4
QA �
QA 👍
1f44d

⚠️ Watch out: If a form limits input to “20 characters”, find out whether the application counts code units or visible characters, and test with emoji and accented letters. These are classic boundary-test cases.


🧪 Tester Scenario: Clean and Check UI Text

Text from a web page often contains extra spaces, line breaks and different case. This helper normalises text before comparing, and a second helper extracts values from a summary line:

📄 ui-text.js

function normalise(text) {
  return text.replace(/\s+/g, " ").trim().toLowerCase();
}

function expectTextEquals(actual, expected) {
  const ok = normalise(actual) === normalise(expected);
  console.log(`${ok ? "PASS" : "FAIL"}: "${normalise(actual)}" vs "${normalise(expected)}"`);
  return ok;
}

expectTextEquals("  Welcome back,\n   ASHA!  ", "Welcome back, Asha!");
expectTextEquals("Order #451 shipped", "Order #452 shipped");

const summary = "Showing 1–25 of 1,204 results for \"laptop\"";
const total = Number(summary.slice(summary.indexOf("of ") + 3, summary.indexOf(" results")).replaceAll(",", ""));
const term = summary.slice(summary.indexOf("\"") + 1, summary.lastIndexOf("\""));
console.log({ total, term });

⌨️ Terminal

node ui-text.js

🖥️ Output

PASS: "welcome back, asha!" vs "welcome back, asha!"
FAIL: "order #451 shipped" vs "order #452 shipped"
{ total: 1204, term: 'laptop' }

Playwright’s toHaveText and toContainText already normalise whitespace, but you need helpers like these when you read text with textContent() and process it yourself.


📝 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 first character, the last character and the length of "automation".

Show answer

📄 practice1.js

const word = "automation";
console.log(word[0], word.at(-1), word.length);

🖥️ Output

a n 10

Q2. Write capitalize(str) that makes the first letter uppercase and the rest lowercase: "pLAYWRIGHT" → "Playwright".

Show answer

📄 practice2.js

const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
console.log(capitalize("pLAYWRIGHT"), capitalize("a"), JSON.stringify(capitalize("")));

🖥️ Output

Playwright A ""

Q3. Count how many times the letter "s" appears in "Tests pass successfully" (case-insensitive).

Show answer

📄 practice3.js

const text = "Tests pass successfully";
const count = text.toLowerCase().split("s").length - 1;
console.log(count);

🖥️ Output

7

Splitting on "s" creates one more piece than there are separators.

Q4. Mask a card number so only the last 4 digits show: "4111111111111111" → "************1111".

Show answer

📄 practice4.js

const card = "4111111111111111";
const masked = card.slice(-4).padStart(card.length, "*");
console.log(masked);

🖥️ Output

************1111

Q5. Convert " Login Page Title Test " into a file-name slug "login-page-title-test.spec.js".

Show answer

📄 practice5.js

const name = "  Login Page Title Test  ";
const file = name.trim().toLowerCase().split(/\s+/).join("-") + ".spec.js";
console.log(file);

🖥️ Output

login-page-title-test.spec.js

Q6. Check whether "Was it a car or a cat I saw" is a palindrome, ignoring spaces and case.

Show answer

📄 practice6.js

const text = "Was it a car or a cat I saw";
const clean = text.toLowerCase().replaceAll(" ", "");
const isPalindrome = clean === [...clean].reverse().join("");
console.log(clean, isPalindrome);

🖥️ Output

wasitacaroracatisaw true

🧠 MCQ Quiz: Strings and String Methods

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What is "JavaScript".length?
  2. What does "tester".at(-1) return?
  3. After let s = "abc"; s.toUpperCase(); what is s?
  4. What does "2026-11-23".slice(5, 7) return?
  5. What does "a,b,c".split(",") return?
  6. What does "1,000,000".replace(",", "") return?
  7. Which method checks whether a string begins with “https”?
  8. What does "QA".indexOf("x") return?
  9. What does "7".padStart(3, "0") return?
  10. Why can "👍".length be 2?

💼 Interview Questions and Answers

Q1. What is the difference between slice, substring and substr?

slice(start, end) extracts from start up to (not including) end and supports negative indexes. substring(start, end) is similar but treats negative values as 0 and swaps the arguments if start is larger than end. substr(start, length) takes a length instead of an end index and is deprecated. In modern code use slice.

Q2. Why are strings immutable, and what does that mean for your code?

Immutable means a string value never changes; methods like trim, replace and toUpperCase return new strings. That makes strings safe to share and compare by value, but you must store or use the returned value. Building a long string in a loop creates many intermediate strings; collecting parts in an array and calling join once is often clearer.

Q3. How do you replace all occurrences of a substring?

Use str.replaceAll("old", "new") (ES2021), or str.replace(/old/g, "new") with a global regex, or the older str.split("old").join("new"). Plain replace with a string pattern replaces only the first occurrence.

📄 replace-all.js

const s = "a-b-c";
console.log(s.replaceAll("-", "+"), s.replace(/-/g, "+"), s.split("-").join("+"));

⌨️ Terminal

node replace-all.js

🖥️ Output

a+b+c a+b+c a+b+c

Q4. How would you reverse a string, and what is the catch?

[...str].reverse().join("") spreads the string into code points, reverses the array and joins it. The older str.split("").reverse().join("") breaks emoji and other characters made of two UTF-16 units. Characters built from several code points (for example family emoji or some accented letters) need Intl.Segmenter to be reversed correctly.

Q5. How do you compare UI text robustly in a test?

Normalise both sides first: collapse whitespace (replace(/\s+/g, " ")), trim, and lower-case if case does not matter. Compare with === after normalising, or use matchers that already normalise (toHaveText). Avoid asserting on text that changes (dates, counters) without extracting and checking the dynamic part separately.


❓ Frequently Asked Questions

🤔 How do I check if a string contains a word in JavaScript?

Use str.includes("word"). For a case-insensitive check, lower-case both: str.toLowerCase().includes("word"). For whole-word matches use a regular expression with \b.

🤔 How do I convert a string to an array?

Use str.split(separator) to split on a separator, or [...str] / Array.from(str) to get individual characters.

🤔 What is the difference between single and double quotes?

None in behaviour. Choose one style for consistency and use the other (or escapes) when the text contains a quote. Back-ticks create template literals.

🤔 How do I remove spaces from a string?

Use trim() for the ends, replaceAll(" ", "") for every space, or replace(/\s+/g, "") for all whitespace including tabs and line breaks.


🏁 Summary

  • Strings are immutable sequences of characters; every method returns a new string.
  • Use length, indexes and at() to read characters; includes, startsWith, indexOf to search.
  • Use slice to extract, trim/padStart/toLowerCase to clean, replaceAll to replace.
  • split turns text into arrays and join turns arrays into text.
  • Normalise whitespace and case before comparing UI text, and remember emoji can count as two characters.

Next, continue with Lesson 26: Template Literals. For extra practice, solve the JavaScript string practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Functions: Declaration, Parameters, Return and Expressions

A function is a reusable block of code with a name. Instead of copying the same login steps, price calculation or date formatting into ten places, you write it once as a function and call it wherever you need it. Every Playwright test is itself a function, and every page object is built from functions. In this lesson you will learn how to declare and call functions, pass data in with parameters, send results back with return, and write small, pure helpers that are easy to test.

📖 What You’ll Learn: what a function is, function declarations, calling functions, parameters versus arguments, return values and early return, functions that return undefined, function expressions, hoisting differences, functions as values, naming and documenting functions, pure functions versus side effects, and writing reusable test helpers.


🧩 What Is a Function?

Definition: a function is a named, reusable block of code that performs a task. It can receive input values (parameters) and send back a result (a return value). Defining a function does not run it; calling it does.

📄 function.js

// 1. Define (declare) the function
function greet(name) {
  return `Hello, ${name}!`;
}

// 2. Call it as many times as you like
console.log(greet("Asha"));
console.log(greet("Ravi"));

const message = greet("QA team");   // store the returned value
console.log(message.length);

⌨️ Terminal

node function.js

🖥️ Output

Hello, Asha!
Hello, Ravi!
15
  • function is the keyword, greet is the name, name is a parameter.
  • greet("Asha") calls the function with the argument "Asha".
  • return sends a value back to the caller, where you can print it, store it or pass it on.

Functions give you three benefits: reuse (write once, call many times), readability (a good name explains the code) and testability (a small function can be checked on its own).


📥 Parameters vs Arguments

Parameters are the names listed in the function definition. Arguments are the actual values you pass when you call it. Arguments are matched to parameters by position.

📄 params.js

function orderSummary(item, qty, price) {   // item, qty, price are parameters
  return `${qty} x ${item} = ${(qty * price).toFixed(2)}`;
}

console.log(orderSummary("Pen", 3, 10));   // "Pen", 3, 10 are arguments

// Missing arguments are undefined; extra arguments are ignored
console.log(orderSummary("Pen", 3));
console.log(orderSummary("Pen", 3, 10, "ignored"));

⌨️ Terminal

node params.js

🖥️ Output

3 x Pen = 30.00
3 x Pen = NaN
3 x Pen = 30.00

⚠️ Watch out: JavaScript does not check how many arguments you pass. A missing argument silently becomes undefined, which turns arithmetic into NaN. The next lessons show default parameters and validation to protect against this.

Functions receive copies of primitive values but references to objects. Changing an object parameter changes the caller’s object too:

📄 by-reference.js

function addTag(test, tag) {
  test.tags.push(tag);      // changes the caller's object
  tag = "changed";          // only changes the local copy
}

const test = { name: "login", tags: ["smoke"] };
const newTag = "regression";
addTag(test, newTag);
console.log(test.tags, newTag);

⌨️ Terminal

node by-reference.js

🖥️ Output

[ 'smoke', 'regression' ] regression

📤 Return Values

return ends the function immediately and sends a value back. A function without return (or with an empty return;) returns undefined.

📄 return.js

function add(a, b) {
  return a + b;
  console.log("never runs");   // code after return is unreachable
}

function logOnly(a, b) {
  console.log("sum is", a + b);   // prints, but returns nothing
}

console.log(add(2, 3));
const result = logOnly(2, 3);
console.log("logOnly returned:", result);

⌨️ Terminal

node return.js

🖥️ Output

5
sum is 5
logOnly returned: undefined

A function can return any value: a number, a string, an object, an array, even another function. Use an object to return several values at once:

📄 return-object.js

function analyse(times) {
  const total = times.reduce((sum, t) => sum + t, 0);
  return {
    count: times.length,
    average: total / times.length,
    slowest: Math.max(...times),
  };
}

const stats = analyse([320, 410, 1290, 250]);
console.log(stats);
console.log(`Slowest response: ${stats.slowest} ms`);

⌨️ Terminal

node return-object.js

🖥️ Output

{ count: 4, average: 567.5, slowest: 1290 }
Slowest response: 1290 ms

Early return

A return inside an if stops the function early. This is the guard-clause pattern from the if/else lesson:

📄 early-return.js

function discountFor(total) {
  if (total <= 0) return 0;
  if (total >= 5000) return total * 0.1;
  if (total >= 1000) return total * 0.05;
  return 0;
}

for (const t of [-5, 500, 1200, 8000]) {
  console.log(t, "->", discountFor(t));
}

⌨️ Terminal

node early-return.js

🖥️ Output

-5 -> 0
500 -> 0
1200 -> 60
8000 -> 800

📝 Function Expressions

Definition: a function expression creates a function as part of an expression, usually by assigning it to a variable. The function itself can be anonymous (have no name).

📄 expression.js

// Function declaration
function square(n) {
  return n * n;
}

// Function expression stored in a constant
const cube = function (n) {
  return n * n * n;
};

// Arrow function expression (next lesson)
const double = (n) => n * 2;

console.log(square(4), cube(3), double(5));
console.log(typeof cube);

⌨️ Terminal

node expression.js

🖥️ Output

16 27 10
function

The difference: hoisting

Function declarations are hoisted with their body, so you can call them before the line where they are written. Function expressions follow the rules of the variable that holds them, so calling them early fails:

📄 hoisting.js

console.log(declared(2));     // works: declarations are hoisted

function declared(n) {
  return n + 1;
}

console.log(expressed(2));    // fails: the const is in the temporal dead zone

const expressed = function (n) {
  return n + 1;
};

⌨️ Terminal

node hoisting.js

🖥️ Output

3
/home/you/js-course/hoisting.js:7
console.log(expressed(2));    // fails: the const is in the temporal dead zone
            ^

ReferenceError: Cannot access 'expressed' before initialization
    at Object.<anonymous> (/home/you/js-course/hoisting.js:7:13)

Node.js v26.13.0
DeclarationExpression
Syntaxfunction name() {}const name = function () {};
Hoisted with bodyYesNo
Can be anonymousNoYes
Typical useTop-level helpersCallbacks, values stored in objects

🎁 Functions Are Values

In JavaScript, functions are first-class values: you can store them in variables, put them in objects and arrays, pass them to other functions and return them from functions.

📄 values.js

const checks = {
  isPositive: function (n) { return n > 0; },
  isEven: (n) => n % 2 === 0,
};

console.log(checks.isPositive(5), checks.isEven(5));

const steps = [
  () => console.log("open page"),
  () => console.log("fill form"),
  () => console.log("submit"),
];
for (const step of steps) step();

function runTwice(action) {      // a function as an argument
  action();
  action();
}
runTwice(() => console.log("ping"));

⌨️ Terminal

node values.js

🖥️ Output

true false
open page
fill form
submit
ping
ping

Passing functions to other functions is the foundation of callbacks, array methods like map and filter, and every Playwright test('name', async () => {...}) call. The Higher-Order Functions lesson covers it in depth.


✨ Pure Functions vs Side Effects

Definition: a pure function always returns the same output for the same input and changes nothing outside itself. A function with side effects changes something else: a global variable, an object argument, a file, the page, or the console.

📄 pure.js

let runCount = 0;

// Impure: depends on and changes outside state
function nextRunName() {
  runCount++;
  return `run-${runCount}`;
}

// Pure: depends only on its inputs
function runName(n) {
  return `run-${n}`;
}

console.log(nextRunName(), nextRunName());   // different results each call
console.log(runName(1), runName(1));         // always the same

⌨️ Terminal

node pure.js

🖥️ Output

run-1 run-2
run-1 run-1

💡 Tip: Keep calculations (formatting, parsing, validation) in pure functions, and keep side effects (clicking, writing files, calling APIs) in a few clearly named functions. Pure functions are trivial to unit test.


🏷️ Naming and Documenting Functions

  • Start with a verb that says what the function does: calculateTotal, getUser, isValidEmail, formatDate.
  • Use is/has/can for functions that return a boolean.
  • Keep functions small and focused on one job. If you need “and” to describe it, split it.
  • Prefer at most three parameters; for more, pass one options object (covered in the Parameters lesson).

Document public helpers with JSDoc so editors show hints and catch mistakes:

📄 jsdoc.js

/**
 * Formats an amount as Indian rupees.
 * @param {number} amount - The amount in rupees
 * @returns {string} The formatted price, for example "₹1,299.50"
 */
function formatINR(amount) {
  return new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(amount);
}

console.log(formatINR(1299.5));

⌨️ Terminal

node jsdoc.js

🖥️ Output

₹1,299.50

🧪 Tester Scenario: Reusable Test-Data Helpers

Test suites share many small tasks: building users, generating unique emails, checking responses. Putting them into functions keeps every test short and consistent:

📄 helpers.js

function uniqueEmail(prefix = "qa") {
  return `${prefix}+${Date.now()}@sqatools.in`;
}

function buildUser(overrides) {
  return {
    name: "Test User",
    email: uniqueEmail(),
    role: "tester",
    active: true,
    ...overrides,               // override only what a test cares about
  };
}

function expectStatus(response, expected) {
  if (response.status !== expected) {
    throw new Error(`Expected status ${expected} but got ${response.status}`);
  }
  return true;
}

const admin = buildUser({ role: "admin" });
const disabled = buildUser({ active: false, name: "Old Account" });
console.log(admin.role, admin.active, /^qa\+\d+@sqatools\.in$/.test(admin.email));
console.log(disabled.name, disabled.active);

console.log(expectStatus({ status: 201 }, 201));
try {
  expectStatus({ status: 500 }, 201);
} catch (e) {
  console.log(e.message);
}

⌨️ Terminal

node helpers.js

🖥️ Output

admin true true
Old Account false
true
Expected status 201 but got 500
  • prefix = "qa" is a default parameter, used when no argument is passed.
  • ...overrides copies the properties passed in over the defaults (spread syntax, covered in Module 6).
  • expectStatus throws an error with a clear message, which is how assertions fail a test.

📝 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 celsiusToFahrenheit(c) that returns c * 9 / 5 + 32, and print the results for 0, 37 and 100.

Show answer

📄 practice1.js

function celsiusToFahrenheit(c) {
  return (c * 9) / 5 + 32;
}

for (const c of [0, 37, 100]) {
  console.log(`${c}°C = ${celsiusToFahrenheit(c)}°F`);
}

🖥️ Output

0°C = 32°F
37°C = 98.6°F
100°C = 212°F

Q2. Write isEven(n) that returns a boolean, then use it to print the even numbers in [3, 8, 11, 14, 20].

Show answer

📄 practice2.js

function isEven(n) {
  return n % 2 === 0;
}

for (const n of [3, 8, 11, 14, 20]) {
  if (isEven(n)) console.log(n);
}

🖥️ Output

8
14
20

Q3. What does this print, and why?

function total(a, b) {
  a + b;
}
console.log(total(2, 3));
Show answer

📄 practice3.js

function total(a, b) {
  a + b;
}
console.log(total(2, 3));

🖥️ Output

undefined

The function calculates a + b but never returns it, so it returns undefined. Write return a + b;.

Q4. Write minMax(numbers) that returns an object with the smallest and largest number of an array.

Show answer

📄 practice4.js

function minMax(numbers) {
  return { min: Math.min(...numbers), max: Math.max(...numbers) };
}

console.log(minMax([42, 7, 19, 88, 3]));

🖥️ Output

{ min: 3, max: 88 }

Q5. Write passRate(passed, total) that returns the pass percentage rounded to one decimal, and returns 0 when total is 0 (no division by zero).

Show answer

📄 practice5.js

function passRate(passed, total) {
  if (total === 0) return 0;
  return Math.round((passed / total) * 1000) / 10;
}

console.log(passRate(17, 20), passRate(2, 3), passRate(0, 0));

🖥️ Output

85 66.7 0

Q6. Make this function pure: it should not change the array it receives.

function addItem(cart, item) {
  cart.push(item);
  return cart;
}
Show answer

📄 practice6.js

function addItem(cart, item) {
  return [...cart, item];   // new array; the original is untouched
}

const cart = ["pen"];
const updated = addItem(cart, "book");
console.log(cart, updated);

🖥️ Output

[ 'pen' ] [ 'pen', 'book' ]

🧠 MCQ Quiz: Functions

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 a function return if it has no return statement?
  2. In function add(a, b) {} and add(2, 3), what are 2 and 3?
  3. What is the value of a parameter when no argument is passed?
  4. Which can be called before the line where it is defined?
  5. What happens to code after a return statement in the same block?
  6. Which describes a pure function?
  7. What is the result?
    function f(obj) { obj.n = 2; }
    const o = { n: 1 };
    f(o);
    console.log(o.n);
  8. How can a function return two values?
  9. Which name best follows conventions for a function that checks a login state?
  10. What does typeof function () {} return?

💼 Interview Questions and Answers

Q1. What is the difference between a function declaration and a function expression?

A declaration (function name() {}) is a statement that creates a named binding hoisted with its body, so it can be called anywhere in its scope. An expression (const name = function () {} or an arrow function) creates the function as a value when that line runs; it follows the hoisting rules of the variable (TDZ for let/const) and can be anonymous. Expressions are used for callbacks and conditional definitions.

Q2. Are arguments passed by value or by reference in JavaScript?

Always by value, but for objects the value is a reference. Reassigning the parameter inside the function does not affect the caller, while mutating the object it points to does. That is why helpers that modify shared test data can cause flaky tests, and why pure functions return new objects instead.

Q3. What are first-class functions?

A language has first-class functions when functions are values like any other: they can be assigned to variables, stored in data structures, passed as arguments and returned from other functions. JavaScript supports all of this, which enables callbacks, higher-order functions such as map, closures and the test(name, fn) style of test frameworks.

Q4. Why are small pure functions valuable in test automation?

They are deterministic, so their results can be checked with simple unit tests and they never cause flakiness. They can be reused across UI and API tests (formatting prices, parsing tables, building payloads) and composed into larger helpers. Keeping side effects in a few places (page objects, API clients) makes failures easier to locate.

Q5. What does this code print?

📄 interview.js

function f() {
  return
  { ok: true };
}
console.log(f());
console.log(typeof f, f.length, f.name);

⌨️ Terminal

node interview.js

🖥️ Output

undefined
function 0 f

Automatic semicolon insertion ends the return at the line break, so f() returns undefined. f.length is the number of declared parameters (0) and f.name is the function’s name.


❓ Frequently Asked Questions

🤔 What are the types of functions in JavaScript?

Function declarations, function expressions, arrow functions, methods (functions stored in objects), constructor functions and classes, async functions and generator functions. This module covers the first three in detail.

🤔 Can a JavaScript function return multiple values?

Not directly, but it can return an array or object containing several values, which the caller can unpack with destructuring: const { min, max } = minMax(list);.

🤔 What is the difference between a function and a method?

A method is a function stored as a property of an object and usually called on that object, for example "text".toUpperCase() or page.click().

🤔 How many parameters should a function have?

Ideally three or fewer. For more, pass a single options object such as createUser({ name, role, active }), which also makes calls self-documenting.


🏁 Summary

  • A function is reusable code: declare it once, call it many times; it runs only when called.
  • Parameters are names in the definition; arguments are the values passed; missing arguments are undefined.
  • return sends a value back and ends the function; without it the result is undefined.
  • Function declarations are hoisted with their body; function expressions are not.
  • Functions are values; keep calculations pure and side effects in clearly named helpers.

Next, continue with Lesson 18: Arrow Functions. For extra practice, solve the JavaScript function practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

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

Loops repeat code: check every row in a table, retry a request until it succeeds, run the same test with ten sets of data. JavaScript has several loop types, and choosing the right one makes code shorter and avoids bugs such as skipping the last item or looping forever. In this lesson you will learn every loop, the difference between for...of and for...in, nested loops, and the important rule for using await inside loops.

📖 What You’ll Learn: the for loop and its three parts, while and do…while, for…of for arrays, strings and Maps, for…in for object keys, Array.forEach, Object.entries, nested loops, infinite loops and how to avoid them, off-by-one errors, choosing the right loop, and await inside loops.


🔁 What Is a Loop?

Definition: a loop runs a block of code repeatedly, either a fixed number of times or while a condition stays true. Each run of the block is called an iteration.

LoopBest for
forCounting: a known number of iterations, or when you need the index
whileRepeating until a condition changes (unknown number of iterations)
do...whileLike while, but the body must run at least once
for...ofValues of arrays, strings, Maps, Sets
for...inKeys (property names) of an object
array.forEach()Calling a function for each array item

🔢 The for Loop

A for loop has three parts in its parentheses, separated by semicolons:

📄 Syntax

for (initialisation; condition; update) {
  // body
}
  1. Initialisation runs once before the loop, usually let i = 0.
  2. Condition is checked before every iteration; the loop stops when it is falsy.
  3. Update runs after every iteration, usually i++.

📄 for.js

for (let i = 1; i <= 5; i++) {
  console.log(`Run ${i} of 5`);
}

const browsers = ["chromium", "firefox", "webkit"];
for (let i = 0; i < browsers.length; i++) {
  console.log(i, browsers[i]);
}

for (let i = 10; i > 0; i -= 3) {   // counting down in steps of 3
  console.log("countdown", i);
}

⌨️ Terminal

node for.js

🖥️ Output

Run 1 of 5
Run 2 of 5
Run 3 of 5
Run 4 of 5
Run 5 of 5
0 chromium
1 firefox
2 webkit
countdown 10
countdown 7
countdown 4
countdown 1

⚠️ Watch out: Off-by-one errors are the most common loop bug. Array indexes go from 0 to length - 1, so the condition is i < arr.length, not i <= arr.length. Using <= reads one item past the end, which is undefined.

📄 off-by-one.js

const items = ["pen", "book"];
for (let i = 0; i <= items.length; i++) {   // bug: <= instead of <
  console.log(i, items[i]);
}

⌨️ Terminal

node off-by-one.js

🖥️ Output

0 pen
1 book
2 undefined

⏳ The while Loop

A while loop checks its condition before each iteration and runs as long as it is truthy. Use it when you do not know in advance how many iterations you need.

📄 while.js

let attempt = 0;
let connected = false;

while (!connected && attempt < 5) {
  attempt++;
  connected = attempt === 3;          // pretend the 3rd attempt works
  console.log(`Attempt ${attempt}: ${connected ? "connected" : "failed"}`);
}
console.log(connected ? "Ready" : "Gave up after 5 attempts");

⌨️ Terminal

node while.js

🖥️ Output

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

⚠️ Watch out: If nothing inside the loop ever makes the condition false, you get an infinite loop and the program hangs. Always change something the condition depends on, and add a safety limit such as attempt < 5. Stop a hanging Node.js script with Ctrl+C.


🔂 The do…while Loop

do...while runs the body first and checks the condition afterwards, so the body always runs at least once.

📄 do-while.js

let page = 1;
const totalPages = 1;   // the API reports only one page

do {
  console.log(`Fetching page ${page}`);
  page++;
} while (page <= totalPages);

let count = 10;
while (count < 5) {
  console.log("while: never printed");
}
do {
  console.log("do...while: printed once even though 10 < 5 is false");
} while (count < 5);

⌨️ Terminal

node do-while.js

🖥️ Output

Fetching page 1
do...while: printed once even though 10 < 5 is false

📋 for…of: Loop Over Values

for...of loops over the values of an iterable: arrays, strings, Maps, Sets and more. It is the cleanest loop for arrays when you do not need the index.

📄 for-of.js

const tests = ["login", "search", "checkout"];
for (const test of tests) {
  console.log("running", test);
}

for (const ch of "QA!") {
  console.log(ch);
}

const scores = new Map([["asha", 91], ["ravi", 78]]);
for (const [name, score] of scores) {
  console.log(name, score);
}

for (const [index, test] of tests.entries()) {   // value and index
  console.log(index + 1, test);
}

⌨️ Terminal

node for-of.js

🖥️ Output

running login
running search
running checkout
Q
A
!
asha 91
ravi 78
1 login
2 search
3 checkout

💡 Tip: Use const in for...of when you do not reassign the loop variable. Each iteration gets a fresh binding, so const is allowed.


🗝️ for…in: Loop Over Object Keys

for...in loops over the keys (property names) of an object. Read the value with bracket notation obj[key].

📄 for-in.js

const config = { browser: "chromium", headless: true, retries: 2 };

for (const key in config) {
  console.log(`${key} = ${config[key]}`);
}

// Object.entries gives key and value together, and works with for...of
for (const [key, value] of Object.entries(config)) {
  console.log(key.padEnd(9), "->", value);
}

⌨️ Terminal

node for-in.js

🖥️ Output

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

⚠️ Watch out: Do not use for...in on arrays. It gives you the indexes as strings and also includes any extra properties added to the array. Use for...of, a classic for or forEach for arrays.

📄 for-in-array.js

const list = ["a", "b"];
list.note = "extra property";

for (const i in list) {
  console.log(i, typeof i);
}
for (const value of list) {
  console.log(value);
}

⌨️ Terminal

node for-in-array.js

🖥️ Output

0 string
1 string
note string
a
b
for...offor...in
Gives youValuesKeys (as strings)
Works onIterables: arrays, strings, Map, SetObjects (any object)
Use for arrays?YesNo
Plain objectsNo (TypeError: not iterable) — use Object.entries()Yes

🧾 Array.forEach

array.forEach(callback) calls a function once for every item, passing the item, its index and the array. It is common in existing code.

📄 foreach.js

const prices = [120, 80, 45];
let total = 0;

prices.forEach((price, index) => {
  console.log(`item ${index + 1}: ${price}`);
  total += price;
});
console.log("total", total);

⌨️ Terminal

node foreach.js

🖥️ Output

item 1: 120
item 2: 80
item 3: 45
total 245
  • You cannot stop forEach early with break; use for...of or some()/find() when you need to stop.
  • forEach does not wait for async callbacks (see the last section).
  • To build a new array from an existing one, map() and filter() are better choices (Module 6).

🪆 Nested Loops

A loop inside another loop runs the inner loop completely for every iteration of the outer loop. A common use is combining two lists, for example every browser with every viewport:

📄 nested.js

const browsers = ["chromium", "firefox"];
const viewports = ["mobile", "desktop"];

for (const browser of browsers) {
  for (const viewport of viewports) {
    console.log(`test on ${browser} / ${viewport}`);
  }
}

// A multiplication table: rows x columns
for (let r = 1; r <= 3; r++) {
  let row = "";
  for (let c = 1; c <= 4; c++) {
    row += String(r * c).padStart(4);
  }
  console.log(row);
}

⌨️ Terminal

node nested.js

🖥️ Output

test on chromium / mobile
test on chromium / desktop
test on firefox / mobile
test on firefox / desktop
   1   2   3   4
   2   4   6   8
   3   6   9  12

The total work is outer × inner iterations. Two lists of 1,000 items already means 1,000,000 iterations, so watch nested loops on large data.


⏱️ Loops and await (Important for Playwright)

Test code is full of await (you will learn promises and async/await in Module 10). The rule to remember now: await works inside for, for...of and while, but forEach does not wait.

📄 await-loop.js

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function main() {
  console.log("--- for...of waits for each step ---");
  for (const step of ["open", "login", "verify"]) {
    await sleep(10);
    console.log("done:", step);
  }
  console.log("all steps finished");

  console.log("--- forEach does NOT wait ---");
  ["open", "login", "verify"].forEach(async (step) => {
    await sleep(10);
    console.log("done:", step);
  });
  console.log("forEach returned (steps still running!)");
}

main();

⌨️ Terminal

node await-loop.js

🖥️ Output

--- for...of waits for each step ---
done: open
done: login
done: verify
all steps finished
--- forEach does NOT wait ---
forEach returned (steps still running!)
done: open
done: login
done: verify

⚠️ Watch out: In a Playwright test, items.forEach(async (item) => { await page.click(...) }) lets the test finish before the clicks happen, causing random failures. Use for (const item of items) { await ... } instead.


🧪 Tester Scenario: Data-Driven Checks

Running the same check with many inputs is called data-driven testing. A loop over a table of cases keeps it short:

📄 data-driven.js

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

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

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

⌨️ Terminal

node data-driven.js

🖥️ Output

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

Playwright supports the same idea directly: put a test() call inside a for...of loop over your cases, and each case appears as its own test in the report.


📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Print the even numbers from 2 to 20 with a for loop, all on one line.

Show answer

📄 practice1.js

let line = "";
for (let n = 2; n <= 20; n += 2) {
  line += n + " ";
}
console.log(line.trim());

🖥️ Output

2 4 6 8 10 12 14 16 18 20

Q2. Calculate the sum and the average of [12, 7, 30, 5, 16] with a for...of loop.

Show answer

📄 practice2.js

const values = [12, 7, 30, 5, 16];
let sum = 0;
for (const v of values) {
  sum += v;
}
console.log("sum", sum, "average", sum / values.length);

🖥️ Output

sum 70 average 14

Q3. Reverse the string "playwright" with a loop (without reverse()).

Show answer

📄 practice3.js

const word = "playwright";
let reversed = "";
for (let i = word.length - 1; i >= 0; i--) {
  reversed += word[i];
}
console.log(reversed);

🖥️ Output

thgirwyalp

Q4. Count how many times each status appears in ["pass", "fail", "pass", "skip", "pass"], storing the counts in an object.

Show answer

📄 practice4.js

const statuses = ["pass", "fail", "pass", "skip", "pass"];
const counts = {};
for (const s of statuses) {
  counts[s] = (counts[s] ?? 0) + 1;
}
console.log(counts);
for (const key in counts) {
  console.log(`${key}: ${counts[key]}`);
}

🖥️ Output

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

Q5. Use a while loop to find the first power of 2 that is greater than 1000.

Show answer

📄 practice5.js

let power = 1;
let exponent = 0;
while (power <= 1000) {
  power *= 2;
  exponent++;
}
console.log(`2^${exponent} = ${power}`);

🖥️ Output

2^10 = 1024

Q6. Print a right-angled triangle of * with 5 rows using nested loops.

Show answer

📄 practice6.js

for (let row = 1; row <= 5; row++) {
  let line = "";
  for (let col = 1; col <= row; col++) {
    line += "*";
  }
  console.log(line);
}

🖥️ Output

*
**
***
****
*****

A shorter alternative for each line is "*".repeat(row).


🧠 MCQ Quiz: Loops

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

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

💼 Interview Questions and Answers

Q1. What is the difference between for…of and for…in?

for...of iterates the values of iterables (arrays, strings, Maps, Sets, generators) using the iterator protocol. for...in iterates the enumerable keys of any object, including inherited ones, as strings. Use for...of for arrays and for...in (or better Object.keys/Object.entries) for plain objects.

Q2. What is the difference between forEach and for…of?

forEach is an array method that calls a callback for each item; you cannot break out of it, return only ends the current callback, and it does not await async callbacks. for...of is a language loop: it supports break, continue and await, and works on any iterable, not only arrays. In async test code, prefer for...of.

Q3. A Playwright test loops over menu links with forEach and clicks each one, but it passes even when links are broken. Why?

The callback is async, and forEach ignores the promises it returns. The test function reaches its end, so the test is reported as passed, while the clicks and assertions run (and may fail) afterwards or are cancelled when the page closes. Fix: for (const link of links) { await link.click(); await expect(...)... }. Use Promise.all only when the steps can safely run in parallel.

Q4. How do you avoid infinite loops in retry logic?

Always bound the loop: a maximum attempt count or a deadline (Date.now() < start + timeout), update the variables the condition depends on inside the loop, and add a delay between attempts. After the loop, fail with a clear error that includes the last result. Built-in waiting tools (Playwright’s auto-waiting, expect.poll, toPass) handle this for you and are preferred in tests.

📄 bounded-retry.js

function retry(action, maxAttempts = 3) {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const ok = action(attempt);
    console.log(`attempt ${attempt}: ${ok ? "ok" : "failed"}`);
    if (ok) return attempt;
  }
  throw new Error(`Failed after ${maxAttempts} attempts`);
}

retry((n) => n === 2);
try {
  retry(() => false);
} catch (e) {
  console.log(e.message);
}

⌨️ Terminal

node bounded-retry.js

🖥️ Output

attempt 1: failed
attempt 2: ok
attempt 1: failed
attempt 2: failed
attempt 3: failed
Failed after 3 attempts

Q5. What is an off-by-one error? Give an example.

A loop that runs one time too many or too few, usually because of <= versus < or starting at 1 instead of 0. Example: for (let i = 0; i <= arr.length; i++) reads arr[arr.length], which is undefined. Iterating values with for...of avoids index arithmetic entirely, and boundary tests (empty array, one item, last item) catch these bugs.


❓ Frequently Asked Questions

🤔 Which loop is fastest in JavaScript?

For normal data sizes the differences are tiny. Choose for readability: for...of for arrays, for when you need the index or a custom step, while for unknown iteration counts.

🤔 How do I loop through an object in JavaScript?

Use for (const [key, value] of Object.entries(obj)), or for...in for the keys. Object.keys() and Object.values() give arrays of keys or values.

🤔 How do I stop a loop early?

Use break to leave the loop or continue to skip to the next iteration. These are covered in the next lesson. They do not work in forEach.

🤔 Can I use await inside a for loop?

Yes, in an async function, await works in for, for...of, while and do...while, and each iteration waits. It does not work as expected inside forEach.


🏁 Summary

  • for counts with initialisation, condition and update; use i < arr.length to avoid off-by-one errors.
  • while repeats while a condition is true; do...while always runs at least once; always make sure the loop can end.
  • for...of gives values of arrays, strings, Maps and Sets; for...in gives object keys and should not be used on arrays.
  • forEach cannot break and does not wait for await; use for...of in async test code.
  • Loops over tables of inputs and expected results are the basis of data-driven testing.

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

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

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

Programs need to make decisions: retry when a request fails, show an error when a field is empty, mark a test as passed or failed. The if statement is how JavaScript decides which code to run. In this lesson you will learn if, else and else if, combine conditions safely, avoid deep nesting with guard clauses, and replace long if chains with lookup objects.

📖 What You’ll Learn: the if statement, if…else, else if chains and their order, conditions with comparison and logical operators, truthy checks, nested if statements, guard clauses and early returns, the ternary alternative, lookup objects, and common mistakes such as = instead of ===.


🚦 The if Statement

Definition: an if statement runs a block of code only when its condition is truthy. The condition goes in parentheses and the code in curly braces.

📄 Syntax

if (condition) {
  // runs only when condition is truthy
}

📄 if.js

const statusCode = 500;

if (statusCode >= 500) {
  console.log("Server error: retry the request");
}

console.log("Check finished");   // always runs

⌨️ Terminal

node if.js

🖥️ Output

Server error: retry the request
Check finished

The condition can be any expression. It is converted to a boolean using the truthy/falsy rules from the Truthy, Falsy and Equality lesson.

💡 Tip: JavaScript allows if (x) doSomething(); without braces for a single statement. Always use braces anyway: adding a second line later without braces is a classic bug, because only the first line belongs to the if.


↔️ if…else

else adds a block that runs when the condition is falsy. Exactly one of the two blocks runs.

📄 if-else.js

function checkLogin(password) {
  if (password.length >= 8) {
    console.log("Password accepted");
  } else {
    console.log(`Password too short: ${password.length} characters`);
  }
}

checkLogin("secret123");
checkLogin("abc");

⌨️ Terminal

node if-else.js

🖥️ Output

Password accepted
Password too short: 3 characters

🪜 else if Chains

Use else if to test several conditions in order. JavaScript runs the first block whose condition is truthy and skips all the others.

📄 else-if.js

function grade(score) {
  if (score >= 90) {
    return "A";
  } else if (score >= 75) {
    return "B";
  } else if (score >= 60) {
    return "C";
  } else {
    return "F";
  }
}

for (const s of [95, 82, 60, 41]) {
  console.log(s, "->", grade(s));
}

⌨️ Terminal

node else-if.js

🖥️ Output

95 -> A
82 -> B
60 -> C
41 -> F

⚠️ Watch out: Order matters. If the first condition were score >= 60, a score of 95 would match it first and get a C. Put the most specific (or highest) conditions first.

📄 wrong-order.js

function gradeWrongOrder(score) {
  if (score >= 60) return "C";      // matches 95 before the A check
  else if (score >= 90) return "A";
  return "F";
}
console.log(gradeWrongOrder(95));

⌨️ Terminal

node wrong-order.js

🖥️ Output

C

🔗 Combining Conditions with &&, || and !

📄 combined.js

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

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

⌨️ Terminal

node combined.js

🖥️ Output

Checkout allowed
Please log in
Cart is empty
Fix cart errors first
  • &&: all parts must be truthy.
  • ||: at least one part must be truthy, for example if (role === "admin" || role === "owner").
  • !: negates a condition. Prefer positive names (isValid) so you rarely need double negatives.

When you compare one value with many options, includes is shorter than a long || chain:

📄 includes.js

const role = "editor";

if (role === "admin" || role === "owner" || role === "editor") {
  console.log("can edit (|| chain)");
}
if (["admin", "owner", "editor"].includes(role)) {
  console.log("can edit (includes)");
}

⌨️ Terminal

node includes.js

🖥️ Output

can edit (|| chain)
can edit (includes)

🪆 Nested if and Guard Clauses

An if can contain another if. A little nesting is fine, but deep nesting is hard to read:

📄 nested.js

function processOrder(order) {
  if (order) {
    if (order.items.length > 0) {
      if (order.paid) {
        return `Shipping order ${order.id}`;
      } else {
        return "Waiting for payment";
      }
    } else {
      return "Order has no items";
    }
  } else {
    return "No order";
  }
}
console.log(processOrder({ id: 7, items: ["pen"], paid: true }));

⌨️ Terminal

node nested.js

🖥️ Output

Shipping order 7

Definition: a guard clause checks for an invalid case at the start of a function and returns early. The remaining code then handles only the normal case, with no nesting:

📄 guard.js

function processOrder(order) {
  if (!order) return "No order";
  if (order.items.length === 0) return "Order has no items";
  if (!order.paid) return "Waiting for payment";

  return `Shipping order ${order.id}`;
}

console.log(processOrder(null));
console.log(processOrder({ id: 8, items: [], paid: true }));
console.log(processOrder({ id: 9, items: ["lamp"], paid: false }));
console.log(processOrder({ id: 10, items: ["lamp"], paid: true }));

⌨️ Terminal

node guard.js

🖥️ Output

No order
Order has no items
Waiting for payment
Shipping order 10

💡 Tip: Guard clauses are the most useful refactoring for beginners. Test helpers, page objects and API clients written this way are much easier to read in a code review.


⚡ Shorter Alternatives: Ternary and Lookup Objects

When an if...else only chooses between two values, the ternary operator is shorter:

📄 ternary.js

const passed = 18, total = 20;

let verdict;
if (passed === total) {
  verdict = "PASS";
} else {
  verdict = "FAIL";
}
console.log(verdict);

const verdict2 = passed === total ? "PASS" : "FAIL";   // same result, one line
console.log(verdict2);

⌨️ Terminal

node ternary.js

🖥️ Output

FAIL
FAIL

When an else if chain maps fixed keys to values, a lookup object is clearer and easier to extend:

📄 lookup.js

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

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

⌨️ Terminal

node lookup.js

🖥️ Output

200 OK
404 Not Found
418 Unknown status

⚠️ Common Mistakes

Using = instead of ===

A single = assigns a value, and the assigned value is then used as the condition. This compiles but is almost always a bug:

📄 assign-bug.js

let env = "qa";

if (env = "prod") {           // bug: assigns "prod", which is truthy
  console.log("Running against PRODUCTION!");
}
console.log("env is now:", env);

⌨️ Terminal

node assign-bug.js

🖥️ Output

Running against PRODUCTION!
env is now: prod

Fix: use ===. ESLint’s no-cond-assign rule reports this mistake.

Comparing a range incorrectly

📄 range-bug.js

const age = 40;
console.log(18 < age < 30);            // (18 < 40) is true, then true < 30 -> 1 < 30
console.log(age > 18 && age < 30);     // correct

⌨️ Terminal

node range-bug.js

🖥️ Output

true
false

JavaScript evaluates 18 < age < 30 left to right: the first comparison becomes true, which converts to 1, and 1 < 30 is true. Always combine two comparisons with &&.

A semicolon after the condition

if (isAdmin); { deleteUser(); } runs deleteUser() every time, because the ; ends the if with an empty statement and the block that follows is just a block. Prettier and ESLint catch this.


🧪 Tester Scenario: Classify Test Results

This function turns raw test results into a readable status, the kind of logic used in custom reporters and CI summaries:

📄 classify.js

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

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

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

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

⌨️ Terminal

node classify.js

🖥️ Output

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

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Write checkAge(age) that prints Minor under 18, Adult from 18 to 59 and Senior from 60. Test it with 15, 18, 59 and 60.

Show answer

📄 practice1.js

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

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

🖥️ Output

15 Minor
18 Adult
59 Adult
60 Senior

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

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

Show answer

📄 practice2.js

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

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

🖥️ Output

2024 leap
1900 not leap
2000 leap
2026 not leap

Q3. Rewrite this nested code with guard clauses.

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

📄 practice3.js

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

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

🖥️ Output

Unknown user
Account disabled
Welcome Asha

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

Show answer

📄 practice4.js

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

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

🖥️ Output

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

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

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

📄 practice5.js

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

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

🖥️ Output

firefox -> Gecko
webkit -> WebKit
opera -> unknown

Q6. Find and fix the bug: the code always prints Admin area.

let role = "tester";
if (role = "admin") {
  console.log("Admin area");
} else {
  console.log("Tester area");
}
Show answer

A single = assigns "admin" to role, and the non-empty string is truthy. Use ===:

📄 practice6.js

let role = "tester";
if (role === "admin") {
  console.log("Admin area");
} else {
  console.log("Tester area");
}

🖥️ Output

Tester area

🧠 MCQ Quiz: if, else if, else

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

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

💼 Interview Questions and Answers

Q1. How do if/else and the ternary operator differ?

if/else is a statement: it chooses which block of code to run and can contain any number of statements. The ternary is an expression: it chooses between two values and can be used inside other expressions (assignments, template literals, return statements). Use the ternary for simple value choices and if/else for logic and side effects.

Q2. What are guard clauses and why are they useful?

Guard clauses are checks at the top of a function that return (or throw) early for invalid or special cases. They remove nesting, keep the main path at the lowest indentation level, and make each rule easy to see. In test helpers they produce clear error messages early, for example if (!baseURL) throw new Error("BASE_URL is not set").

Q3. Explain the output of this code.

📄 explain.js

const items = [];
if (items) console.log("has items?");
if (items.length) console.log("really has items");
if ("0") console.log("string zero is truthy");

⌨️ Terminal

node explain.js

🖥️ Output

has items?
string zero is truthy

An empty array is an object, so it is truthy and the first message prints. items.length is 0 (falsy), so the second does not. The string "0" is non-empty and therefore truthy.

Q4. How would you test a function with many if/else branches?

Write at least one test per branch (branch coverage), plus boundary values for each comparison: for score >= 90 test 89, 90 and 91. Include invalid inputs that guard clauses should reject (null, empty arrays, negative numbers). Table-driven tests, an array of input/expected pairs in a loop, keep this compact; Playwright and Jest both support this pattern.

Q5. How can you avoid a long if/else if chain?

  • A lookup object or Map for exact key-to-value mappings.
  • A switch statement for many exact matches with different code (next lesson).
  • Guard clauses for validation rules.
  • Polymorphism (different classes with the same method) for behaviour that varies by type, covered in the OOP module.

❓ Frequently Asked Questions

🤔 Can I write if without curly braces?

Yes, for a single statement, but it is risky because a second line added later would run unconditionally. Most style guides require braces.

🤔 Is there an elseif keyword in JavaScript?

No. JavaScript uses two words, else if. Writing elseif is a syntax error.

🤔 How many else if blocks can I use?

As many as you need, but more than three or four usually means a lookup object, a switch or guard clauses would be clearer.

🤔 What is the difference between if (x) and if (x !== undefined)?

if (x) is false for every falsy value, including 0, “” and false. if (x !== undefined) is true for those values. Use the explicit check when 0 or “” are valid.


🏁 Summary

  • if runs a block when its condition is truthy; else runs when it is not.
  • else if chains test conditions in order and run only the first match, so put specific conditions first.
  • Combine conditions with &&, || and !; use includes for “one of many values”.
  • Guard clauses with early returns replace deep nesting; ternaries and lookup objects replace simple chains.
  • Watch for = instead of ===, chained range comparisons and a stray semicolon after the condition.

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

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Type Conversion and Coercion: Explicit vs Implicit with Examples

Values often arrive as the wrong type. Text from a web page, a form field, a CSV file or a command-line argument is always a string, even when it looks like a number. JavaScript can convert types for you (coercion), but its automatic rules are a famous source of bugs such as "5" + 2 giving "52". In this lesson you will learn to convert values explicitly and safely, understand the implicit rules, and parse real UI text like "₹1,299.50" into numbers you can assert on.

📖 What You’ll Learn: explicit conversion with String(), Number(), Boolean(), parseInt() and parseFloat(), the unary plus, toString() and toFixed(), implicit coercion with +, -, * and comparisons, how null, undefined, empty strings and arrays convert, NaN and Number.isNaN, and parsing numbers and dates from text.


🔄 Conversion vs Coercion

Definition: type conversion means turning a value of one type into another type. When you do it on purpose with a function such as Number("42"), it is explicit conversion. When JavaScript does it automatically because an operator needs a different type, it is implicit conversion, also called type coercion.

📄 intro.js

const fromInput = "42";            // text from a form, a page or process.argv

const explicit = Number(fromInput); // you decide: string -> number
const implicit = fromInput * 2;     // JavaScript decides: * needs numbers

console.log(explicit, typeof explicit);
console.log(implicit, typeof implicit);
console.log(fromInput + 2);         // + with a string joins text instead!

⌨️ Terminal

node intro.js

🖥️ Output

42 number
84 number
422

Values can be converted to only three primitive types: string, number and boolean. Learn the rules for those three and coercion stops being surprising.


🔤 Convert to String

📄 to-string.js

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

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

⌨️ Terminal

node to-string.js

🖥️ Output

123
true
null
undefined
1,2,3
[object Object]
7.5 7.50
ff
42 42
  • String(value) works for every value, including null and undefined.
  • value.toString() throws on null and undefined because they have no methods.
  • Plain objects become "[object Object]". Use JSON.stringify(obj) to turn an object into readable text.

🔢 Convert to Number: Number(), parseInt(), parseFloat()

Number(value) converts the whole value or returns NaN if any part is invalid. parseInt() and parseFloat() read a number from the start of a string and stop at the first invalid character.

📄 to-number.js

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

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

⌨️ Terminal

node to-number.js

🖥️ Output

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

⚠️ Watch out: Number("") and Number(null) return 0, not NaN. An empty form field can therefore silently become the number 0. Check for empty strings before converting user input.

💡 Tip: Always pass the radix (base) to parseInt: parseInt(value, 10). It documents your intent and avoids surprises with strings such as "0x1A", which parseInt reads as hexadecimal.


✅ Convert to Boolean

Boolean(value) (or !!value) converts using a short list of falsy values. Everything not on the list is truthy.

📄 to-boolean.js

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

⌨️ Terminal

node to-boolean.js

🖥️ Output

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

The falsy values are false, 0, -0, 0n, "", null, undefined and NaN. Note that the strings "0" and "false", empty arrays and empty objects are all truthy. The next lessons use this in conditions.


⚠️ Implicit Coercion with Operators

Operators coerce their operands. The rules that matter most:

  • +: if either side is a string, both are converted to strings and joined. Otherwise both become numbers.
  • -, *, /, %, **: always convert both sides to numbers.
  • Comparisons < >: convert to numbers, unless both sides are strings, which are compared alphabetically.
  • Conditions (if, &&, ||, !): convert to boolean.

📄 coercion.js

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

⌨️ Terminal

node coercion.js

🖥️ Output

52
71
152
3
12
2.5
2
1
NaN

1,23
false
true

⚠️ Watch out: Sorting or comparing numbers that are stored as strings gives alphabetical results: "10" < "9" because "1" comes before "9". Convert to numbers before comparing prices, counts or IDs read from a page.


🚫 NaN: Not a Number

Definition: NaN is a special number value that means “the result is not a valid number”. It appears when a conversion or calculation fails. NaN is the only value that is not equal to itself, so value === NaN never works.

📄 nan.js

const qty = Number("two");
console.log(qty, typeof qty);
console.log(qty === NaN);            // always false!
console.log(Number.isNaN(qty));      // correct check

console.log(isNaN("hello"));         // global isNaN converts first -> true
console.log(Number.isNaN("hello"));  // only true for the NaN value itself -> false
console.log(Number.isFinite(Number("1e3")), Number.isFinite(Infinity));

⌨️ Terminal

node nan.js

🖥️ Output

NaN number
false
true
true
false
true false

💡 Tip: To validate that text is a usable number, convert it and check Number.isFinite(n). It rejects NaN, Infinity and -Infinity in one call.


🧪 Tester Scenario: Parse Prices and Counts from UI Text

A page shows "₹1,299.50", "Showing 25 of 1,024 results" or "$0.99". To assert on these values, remove everything except digits, the decimal point and the minus sign, then convert:

📄 parse-ui.js

function parsePrice(text) {
  const cleaned = text.replace(/[^0-9.-]/g, ""); // keep digits, dot and minus
  if (cleaned === "") throw new Error(`No number in "${text}"`);
  const value = Number(cleaned);
  if (!Number.isFinite(value)) throw new Error(`Invalid price "${text}"`);
  return value;
}

const cartLines = ["₹1,299.50", "₹ 450.00", "₹50"];
const total = cartLines.map(parsePrice).reduce((sum, p) => sum + p, 0);
console.log("Line prices:", cartLines.map(parsePrice));
console.log("Total:", total.toFixed(2));

const summary = "Showing 25 of 1,024 results";
const [shown, all] = summary.match(/[\d,]+/g).map((s) => parseInt(s.replace(/,/g, ""), 10));
console.log({ shown, all });

⌨️ Terminal

node parse-ui.js

🖥️ Output

Line prices: [ 1299.5, 450, 50 ]
Total: 1799.50
{ shown: 25, all: 1024 }
  • replace(/[^0-9.-]/g, "") uses a regular expression to delete currency symbols, commas and spaces (Module 5 explains regular expressions).
  • The function throws a clear error for text without a number, so a broken page fails the test instead of comparing NaN.
  • match(/[\d,]+/g) finds every group of digits and commas in the sentence.

⚠️ Watch out: This simple cleaner assumes “.” is the decimal separator. Pages in locales that write 1.299,50 need a locale-aware parser or a fixed test locale (Playwright’s locale option).


📅 Bonus: Dates and JSON Conversion

Two more conversions you will use all the time in tests:

📄 dates-json.js

// Dates <-> numbers and strings
const d = new Date("2026-11-23T10:30:00Z");
console.log(d.getTime());           // milliseconds since 1 Jan 1970 (UTC)
console.log(d.toISOString());       // standard string for APIs
console.log(new Date(0).toISOString());

// Objects <-> JSON text
const payload = { id: 7, tags: ["smoke"], active: true };
const text = JSON.stringify(payload);
console.log(text, typeof text);
const back = JSON.parse(text);
console.log(back.tags[0], typeof back);

⌨️ Terminal

node dates-json.js

🖥️ Output

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

API responses arrive as JSON text and are converted with JSON.parse (Playwright’s response.json() does this for you). The JSON lesson in Module 7 goes further.


📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Convert "19.99", "5" and "0.01" to numbers and print their sum with two decimals.

Show answer

📄 practice1.js

const prices = ["19.99", "5", "0.01"];
const sum = prices.map(Number).reduce((a, b) => a + b, 0);
console.log(sum.toFixed(2));

🖥️ Output

25.00

Q2. Predict each result before running: "3" + 4 + 5, 3 + 4 + "5", "3" * "4", "10" - "4" + "1".

Show answer

📄 practice2.js

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

🖥️ Output

345
75
12
61

Evaluation goes left to right. "3" + 4 is already a string, so 5 is appended. 3 + 4 is 7 before meeting the string. "10" - "4" is the number 6, then + "1" joins text.

Q3. Write toQuantity(text) that returns a whole number from input such as " 3 ", and throws an error for "", "abc" or "2.5".

Show answer

📄 practice3.js

function toQuantity(text) {
  const trimmed = String(text).trim();
  const n = Number(trimmed);
  if (trimmed === "" || !Number.isInteger(n)) {
    throw new Error(`Invalid quantity: "${text}"`);
  }
  return n;
}

console.log(toQuantity(" 3 "));
for (const bad of ["", "abc", "2.5"]) {
  try {
    toQuantity(bad);
  } catch (e) {
    console.log(e.message);
  }
}

🖥️ Output

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

The empty-string check is needed because Number("") is 0, a valid integer.

Q4. An array of order IDs read from a table is ["10", "9", "100", "25"]. Sort it numerically from smallest to largest.

Show answer

📄 practice4.js

const ids = ["10", "9", "100", "25"];
console.log([...ids].sort());                    // alphabetical: wrong
console.log(ids.map(Number).sort((a, b) => a - b)); // numeric: right

🖥️ Output

[ '10', '100', '25', '9' ]
[ 9, 10, 25, 100 ]

Q5. Print the boolean value of "0", 0, "false", [] and "" using !!.

Show answer

📄 practice5.js

for (const v of ["0", 0, "false", [], ""]) {
  console.log(JSON.stringify(v), !!v);
}

🖥️ Output

"0" true
0 false
"false" true
[] true
"" false

Q6. Extract the rating number from "Rated 4.5 out of 5 (1,203 reviews)" as a number, and the review count as a whole number.

Show answer

📄 practice6.js

const text = "Rated 4.5 out of 5 (1,203 reviews)";
const rating = parseFloat(text.match(/[\d.]+/)[0]);
const reviews = parseInt(text.match(/\(([\d,]+)/)[1].replace(/,/g, ""), 10);
console.log(rating, reviews, typeof rating, typeof reviews);

🖥️ Output

4.5 1203 number number

🧠 MCQ Quiz: Type Conversion and Coercion

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

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

💼 Interview Questions and Answers

Q1. What is the difference between type conversion and type coercion?

Conversion is explicit: you call Number(), String(), Boolean(), parseInt() and so on. Coercion is implicit: the engine converts automatically because an operator or context needs another type, for example "5" * 2, if (value) or "a" + 1. Coercion only ever produces strings, numbers or booleans.

Q2. What is the difference between Number(), parseInt() and parseFloat()?

Number() converts the entire value and returns NaN if anything is invalid (Number("12px") is NaN), and treats "", null and false as 0. parseInt(str, radix) parses an integer from the beginning of a string and stops at the first invalid character. parseFloat() does the same but keeps decimals. Use Number() for strict validation and the parse functions for strings with units.

Q3. Explain the output of these expressions.

📄 tricky.js

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

⌨️ Terminal

node tricky.js

🖥️ Output

[object Object]
11
2
baNaNa
  • [] + {}: both convert to strings, "" and "[object Object]".
  • 1 + "2" is "12", then - 1 converts back to a number: 11.
  • true + true: booleans become 1 + 1 = 2.
  • +"a" is NaN, which is joined as text, giving "baNaNa".

Q4. How do you safely read a number from text on a web page in a test?

  1. Get the text (for example await locator.textContent()) and trim it.
  2. Remove formatting such as currency symbols, thousands separators and units with a regular expression.
  3. Convert with Number() and validate with Number.isFinite(); throw a clear error if it fails.
  4. Compare with a tolerance for decimals, or compare integer cents, to avoid floating-point issues.
  5. Fix the test locale so number formatting is predictable.

Q5. Why is isNaN() considered unreliable?

The global isNaN(x) first converts x to a number, so isNaN("hello") is true even though "hello" is a string, not the NaN value. Number.isNaN(x) does not convert and returns true only for NaN itself. For input validation, Number.isFinite(Number(x)) is usually what you want.


❓ Frequently Asked Questions

🤔 How do I convert a string to a number in JavaScript?

Use Number(str) when the whole string must be a number, or parseInt(str, 10) / parseFloat(str) when it starts with a number followed by other text, such as "12px". Check the result with Number.isFinite().

🤔 How do I convert a number to a string?

Use String(n), n.toString() or a template literal `${n}`. Use n.toFixed(2) for a fixed number of decimal places.

🤔 Why does “1” + 1 equal “11”?

When either side of + is a string, JavaScript converts the other side to a string and joins them. Convert the string first: Number("1") + 1 is 2.

🤔 Is it bad to rely on type coercion?

Coercion in conditions (if (items.length)) is normal and readable. Coercion in arithmetic and equality (==) causes bugs, so convert explicitly and use ===.


🏁 Summary

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

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

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

JavaScript Data Types: Primitives, Objects and typeof Explained

Every value in JavaScript has a type: "Asha" is a string, 42 is a number, true is a boolean. The type decides what you can do with a value and how it behaves when you copy or compare it. In this lesson you will learn all eight JavaScript data types, how to check a type with typeof (and its traps), and the difference between primitive and reference values that causes so many test-data bugs.

📖 What You’ll Learn: the seven primitive types (string, number, bigint, boolean, undefined, null, symbol), the object type and its kinds (arrays, functions, dates), the typeof operator and its quirks, Array.isArray, null versus undefined, immutability of primitives, and copying by value versus by reference.


🧬 What Is a Data Type?

Definition: a data type describes what kind of value something is and which operations make sense for it. JavaScript has 8 data types: seven primitive types and one object type.

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

Because JavaScript is dynamically typed, a variable has no fixed type; the value has the type.


🔤 The Primitive Types

Definition: a primitive is a simple value that is not an object and has no properties of its own. Primitives are immutable: you cannot change a primitive value, you can only replace it with another.

📄 primitives.js

const name = "Asha";               // string
const age = 29;                    // number (integers and decimals share one type)
const price = 499.99;              // number
const views = 12345678901234567890n; // bigint (note the n)
const isActive = true;             // boolean
let nickname;                      // undefined (declared, not assigned)
const middleName = null;           // null (deliberately empty)
const id = Symbol("id");           // symbol

console.log(typeof name, typeof age, typeof price);
console.log(typeof views, typeof isActive, typeof nickname);
console.log(typeof middleName, typeof id);

⌨️ Terminal

node primitives.js

🖥️ Output

string number number
bigint boolean undefined
object symbol
  • string: text in double quotes, single quotes or back-ticks. Back-ticks allow ${...} placeholders.
  • number: one type for integers and decimals, plus the special values Infinity, -Infinity and NaN (“not a number”).
  • bigint: integers of any size, written with an n suffix. Covered in the Numbers lesson.
  • symbol: every Symbol() is unique, even with the same description. Libraries use symbols for hidden property keys.

Strings look like they have methods, and they do, but calling a method never changes the original string:

📄 immutable.js

let status = "passed";
const upper = status.toUpperCase();
console.log(status, upper);   // the original is unchanged

status[0] = "P";              // ignored: strings are immutable
console.log(status);

console.log(Symbol("id") === Symbol("id")); // every symbol is unique

⌨️ Terminal

node immutable.js

🖥️ Output

passed PASSED
passed
false

🗂️ The Object Type: Objects, Arrays, Functions and More

Definition: an object is a collection of properties (key–value pairs). Everything that is not a primitive is an object, including arrays, functions, dates, maps and regular expressions.

📄 objects.js

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

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

⌨️ Terminal

node objects.js

🖥️ Output

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

🔍 The typeof Operator and Its Quirks

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

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

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

📄 typename.js

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

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

⌨️ Terminal

node typename.js

🖥️ Output

"text"       -> string
7            -> number
NaN          -> number
5n           -> bigint
true         -> boolean
undefined    -> undefined
null         -> null
[1]          -> array
{ a: 1 }     -> object
new Date()   -> date
() => {}     -> function

💡 Tip: To check for null reliably, compare directly: value === null. Never rely on typeof value === "object" alone, because null passes that check too.


🕳️ undefined vs null

Both mean “no value”, but they are used differently:

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

📄 null-undefined.js

const order = { id: 101, coupon: null };

let shippedAt;
function log() {}

console.log(shippedAt);          // never assigned
console.log(order.trackingNo);    // property does not exist
console.log(log());              // function with no return value
console.log(order.coupon);       // explicitly empty

console.log(JSON.stringify({ a: undefined, b: null }));
console.log(null == undefined, null === undefined);

⌨️ Terminal

node null-undefined.js

🖥️ Output

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

The last line previews the next lessons: loose equality == treats null and undefined as equal, strict equality === does not.


📋 Copy by Value vs Copy by Reference

This is the most important difference between primitives and objects, and a frequent source of test bugs.

  • Primitives are copied by value. The new variable gets its own copy.
  • Objects are copied by reference. The new variable points to the same object, so a change through one name is visible through the other.

📄 reference.js

let a = 10;
let b = a;       // copy of the value
b = 20;
console.log("primitives:", a, b);

const original = { user: "asha", role: "tester" };
const copy = original;          // copy of the reference (same object)
copy.role = "admin";
console.log("objects:", original.role, copy.role);
console.log("same object?", original === copy);

⌨️ Terminal

node reference.js

🖥️ Output

primitives: 10 20
objects: admin admin
same object? true

To get an independent copy of an object, create a new one. structuredClone() makes a deep copy, including nested objects:

📄 clone.js

const baseUser = { name: "asha", address: { city: "Pune" } };

const shallow = { ...baseUser };          // new top-level object
const deep = structuredClone(baseUser);   // new object at every level

shallow.name = "ravi";
shallow.address.city = "Delhi";           // nested object is still shared!
deep.address.city = "Mumbai";

console.log(baseUser);
console.log(deep);

⌨️ Terminal

node clone.js

🖥️ Output

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

⚠️ Watch out: A common flaky-test pattern: a shared test-data object is modified by one test, and the next test receives the changed data. Build fresh data for each test, or clone a template with structuredClone().

The same rule applies to comparison: two objects are equal only if they are the same object.

📄 compare.js

console.log({ id: 1 } === { id: 1 });   // two different objects
console.log([1, 2] === [1, 2]);
const x = { id: 1 };
const y = x;
console.log(x === y);                   // same reference

⌨️ Terminal

node compare.js

🖥️ Output

false
false
true

🧪 Tester Scenario: Validate the Types in an API Response

API tests often check that each field has the right type, not just the right value. This example validates a user object against a simple schema:

📄 schema-check.js

const response = {
  id: 42,
  email: "qa@sqatools.in",
  active: true,
  roles: ["tester"],
  manager: null,
  createdAt: "2026-11-23T10:00:00Z",
};

const schema = {
  id: "number",
  email: "string",
  active: "boolean",
  roles: "array",
  manager: "null",
  createdAt: "string",
};

function typeName(v) {
  if (v === null) return "null";
  if (Array.isArray(v)) return "array";
  return typeof v;
}

let errors = 0;
for (const field in schema) {
  const actual = typeName(response[field]);
  const ok = actual === schema[field];
  if (!ok) errors++;
  console.log(`${ok ? "PASS" : "FAIL"} ${field}: expected ${schema[field]}, got ${actual}`);
}
console.log(errors === 0 ? "Schema check passed" : `${errors} field(s) failed`);

⌨️ Terminal

node schema-check.js

🖥️ Output

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

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


📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Print the typeof result for "42", 42, 42n, [42] and { n: 42 }.

Show answer

📄 practice1.js

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

🖥️ Output

string
number
bigint
object
object

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

Show answer

📄 practice2.js

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

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

🖥️ Output

true
false
false
false

Q3. Predict the output, then run it.

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

📄 practice3.js

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

🖥️ Output

5 5 10

saved and cart are the same object, so both show 5. count received a copy of the number 5, so changing it to 10 does not affect the object.

Q4. Create a test-data template { name: "asha", tags: ["ui"] }. Make an independent copy, add "api" to the copy’s tags, and show that the template did not change.

Show answer

📄 practice4.js

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

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

🖥️ Output

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

A spread copy { ...template } would share the same tags array, so the template would change too.

Q5. Which of these values are primitives: "abc", null, [], Symbol(), new Date(), 0n, function(){}?

Show answer

Primitives: "abc", null, Symbol(), 0n. Objects: [], new Date(), function(){}.

Q6. An API returns { discount: null } for one product and {} for another. Write code that prints no discount field, discount is empty or the discount value for each case.

Show answer

📄 practice6.js

function describe(product) {
  if (product.discount === undefined) return "no discount field";
  if (product.discount === null) return "discount is empty";
  return `discount ${product.discount}%`;
}

console.log(describe({ discount: null }));
console.log(describe({}));
console.log(describe({ discount: 15 }));

🖥️ Output

discount is empty
no discount field
discount 15%

🧠 MCQ Quiz: Data Types

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

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

💼 Interview Questions and Answers

Q1. List the JavaScript data types and say which are primitives.

There are eight: string, number, bigint, boolean, undefined, null and symbol are primitives; object covers everything else, including arrays, functions, dates, maps, sets and regular expressions. Primitives are immutable and compared by value; objects are mutable and compared by reference.

Q2. What is the difference between null and undefined?

undefined means a value was never assigned: unassigned variables, missing properties, missing arguments and functions without return. null is an explicit “no value” that a developer or API sets on purpose. typeof undefined is "undefined" while typeof null is "object"; null == undefined is true but null === undefined is false; JSON keeps null but drops undefined properties.

Q3. How do you reliably check whether a value is an array, an object or null?

📄 check.js

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

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

⌨️ Terminal

node check.js

🖥️ Output

null array object number

For more precise names, Object.prototype.toString.call(v) returns strings such as "[object Date]".

Q4. Explain pass-by-value and pass-by-reference in JavaScript.

JavaScript always passes arguments by value, but for objects the value is a reference. So a function that changes a property of an object argument changes the caller’s object, while reassigning the parameter to a new object does not affect the caller. Primitives are copied, so changes inside the function never leak out.

📄 pass.js

function update(user, count) {
  user.name = "changed";   // visible to the caller
  user = { name: "new" };  // only changes the local parameter
  count = 99;              // only changes the local copy
}

const u = { name: "asha" };
let c = 1;
update(u, c);
console.log(u.name, c);

⌨️ Terminal

node pass.js

🖥️ Output

changed 1

Q5. What is the difference between a shallow and a deep copy?

A shallow copy ({ ...obj }, Object.assign({}, obj), [...arr]) creates a new top-level container but nested objects are still shared. A deep copy (structuredClone(obj)) duplicates every level. JSON.parse(JSON.stringify(obj)) is an older deep-copy trick that loses undefined, functions, dates (they become strings), Map and Set.


❓ Frequently Asked Questions

🤔 Is an array a data type in JavaScript?

Not a separate one. Arrays are a kind of object, which is why typeof [] is "object". Use Array.isArray() to detect them.

🤔 Why is typeof null “object”?

In the first implementation of JavaScript, values were stored with a type tag, and the tag for objects was 0. null was represented as a null pointer, also 0, so it was reported as an object. Fixing it would break existing websites.

🤔 Does JavaScript have an integer type?

Regular numbers are all 64-bit floating point, used for both integers and decimals. For integers larger than 253 − 1, use bigint.

🤔 When should I use null instead of undefined?

Use null when you deliberately set “no value”, for example to clear a field or to send an empty value in JSON. Let undefined mean “not set”.


🏁 Summary

  • JavaScript has 8 data types: 7 primitives (string, number, bigint, boolean, undefined, null, symbol) and object.
  • typeof returns the type name, but reports null and arrays as "object"; use === null and Array.isArray().
  • undefined means “not set”; null means “deliberately empty”.
  • Primitives are immutable and copied by value; objects are mutable and copied and compared by reference.
  • Use structuredClone() for independent deep copies of test data.

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

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

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

Operators are the verbs of a programming language: they add prices, compare a status code with 200, combine conditions and pick between two values. You have already met a few; in this lesson you will learn every JavaScript operator you need in real code and tests, how short-circuit evaluation works, how i++ differs from ++i, and how precedence decides what runs first.

📖 What You’ll Learn: arithmetic operators including % and **, increment and decrement, assignment and compound assignment, comparison operators, logical operators and short-circuiting, the conditional (ternary) operator, typeof, instanceof, in, delete, spread, the comma operator, and operator precedence.


➕ Arithmetic Operators

Definition: an operator is a symbol that performs an operation on one or more values, called operands. a + b has two operands (a binary operator); -a has one (a unary operator).

📄 arithmetic.js

const a = 17, b = 5;

console.log("a + b  =", a + b);
console.log("a - b  =", a - b);
console.log("a * b  =", a * b);
console.log("a / b  =", a / b);     // always a decimal division
console.log("a % b  =", a % b);     // remainder
console.log("a ** 2 =", a ** 2);    // exponent (power)
console.log("-a     =", -a);        // unary minus

⌨️ Terminal

node arithmetic.js

🖥️ Output

a + b  = 22
a - b  = 12
a * b  = 85
a / b  = 3.4
a % b  = 2
a ** 2 = 289
-a     = -17
  • / never rounds: 17 / 5 is 3.4. Use Math.floor(a / b) or Math.trunc for whole-number division.
  • % (remainder) is handy for even/odd checks (n % 2 === 0) and for cycling through values.
  • + also joins strings, as you saw in the Type Conversion lesson.

📄 remainder.js

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

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

⌨️ Terminal

node remainder.js

🖥️ Output

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

🔼 Increment and Decrement (++ and –)

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

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

📄 increment.js

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

⌨️ Terminal

node increment.js

🖥️ Output

5
6
7
7
6

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


📝 Assignment Operators

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

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

📄 assignment.js

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

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

⌨️ Terminal

node assignment.js

🖥️ Output

125
Results: 18 passed, 2 failed

⚖️ Comparison Operators

Comparison operators return true or false:

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

📄 comparison.js

const status = 201;
const responseMs = 850;
const limitMs = 1000;

console.log("success:", status >= 200 && status < 300);
console.log("fast enough:", responseMs <= limitMs);
console.log("created:", status === 201);
console.log("not an error:", status !== 500);

⌨️ Terminal

node comparison.js

🖥️ Output

success: true
fast enough: true
created: true
not an error: true

🧠 Logical Operators and Short-Circuiting

OperatorNameResult
a && bANDIf a is falsy, returns a; otherwise returns b
a || bORIf a is truthy, returns a; otherwise returns b
!aNOTtrue if a is falsy, otherwise false
a ?? bNullish coalescingb only if a is null/undefined

With booleans they work as you expect. Note that && and || return one of the operand values, not necessarily true or false:

📄 logical.js

const isLoggedIn = true;
const isAdmin = false;

console.log(isLoggedIn && isAdmin);   // false
console.log(isLoggedIn || isAdmin);   // true
console.log(!isAdmin);                // true

console.log("Asha" && "admin");       // both truthy: returns the second value
console.log("" || "default name");    // first is falsy: returns the second
console.log(0 && "never checked");    // first is falsy: returns 0

⌨️ Terminal

node logical.js

🖥️ Output

false
true
true
admin
default name
0

Short-circuit evaluation: JavaScript stops evaluating as soon as the result is known. The right side of && runs only if the left is truthy; the right side of || runs only if the left is falsy.

📄 short-circuit.js

function sendReport() {
  console.log("report sent");
  return true;
}

const failures = 0;
failures > 0 && sendReport();        // left is false: sendReport never runs
failures === 0 || sendReport();      // left is true: sendReport never runs
console.log("done, no report needed");

const user = null;
console.log(user && user.name);      // safe: stops at null

⌨️ Terminal

node short-circuit.js

🖥️ Output

done, no report needed
null

⚠️ Watch out: Do not use && as a hidden if in team code (isValid && save()); a real if statement is easier to read and debug. Use the operators for conditions and defaults.


❓ The Conditional (Ternary) Operator

Definition: the conditional operator condition ? valueIfTrue : valueIfFalse is the only operator with three operands, so it is often called the ternary operator. It is an expression, so it produces a value you can store or print.

📄 ternary.js

const score = 72;
const result = score >= 60 ? "PASS" : "FAIL";
console.log(`Score ${score}: ${result}`);

const items = 1;
console.log(`${items} ${items === 1 ? "item" : "items"} in cart`);

const ms = 1530;
const label = ms < 500 ? "fast" : ms < 1000 ? "ok" : "slow";  // chained
console.log(`${ms} ms is ${label}`);

⌨️ Terminal

node ternary.js

🖥️ Output

Score 72: PASS
1 item in cart
1530 ms is slow

💡 Tip: One level of ternary is readable; chained ternaries quickly become hard to follow. For three or more branches, use if...else if (next lesson) or a lookup object.


🔎 typeof, instanceof, in and delete

📄 keyword-ops.js

class LoginPage {}
const page = new LoginPage();
const user = { name: "Asha", role: "tester" };

console.log(typeof user.name);               // type of a value
console.log(page instanceof LoginPage);       // created by this class?
console.log([] instanceof Array);
console.log("role" in user, "email" in user); // does the property exist?
console.log(0 in ["a"], 1 in ["a"]);         // index exists in array?

delete user.role;                            // remove a property
console.log(user);

⌨️ Terminal

node keyword-ops.js

🖥️ Output

string
true
true
true false
true false
{ name: 'Asha' }
  • typeof returns a type name as a string (covered in the Data Types lesson).
  • instanceof checks whether an object was created by a class or constructor.
  • in checks whether a property name (or array index) exists, even if its value is undefined.
  • delete removes a property from an object. It does not work on variables.

🌊 Spread (…) and the Comma Operator

The spread syntax ... expands an array or object into individual elements. You will use it constantly; the Destructuring and Spread lesson covers it fully.

📄 spread.js

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

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

⌨️ Terminal

node spread.js

🖥️ Output

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

The comma operator evaluates several expressions and returns the last one. You will mostly see it in for loops that update two variables:

📄 comma.js

for (let i = 0, j = 4; i < j; i++, j--) {
  console.log(i, j);
}

⌨️ Terminal

node comma.js

🖥️ Output

0 4
1 3

📐 Operator Precedence

Definition: precedence decides which operator runs first when an expression has several. Higher precedence runs first; operators with the same precedence run left to right (except ** and assignment, which run right to left).

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

📄 precedence.js

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

⌨️ Terminal

node precedence.js

🖥️ Output

14
20
512
3
true
2

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


📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Print the total price of 3 items at 249.5 each, plus 18% tax, rounded to two decimals.

Show answer

📄 practice1.js

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

🖥️ Output

883.23

Q2. Predict the output, then run it.

let x = 3;
const y = x++ + ++x;
console.log(x, y);
Show answer

📄 practice2.js

let x = 3;
const y = x++ + ++x;
console.log(x, y);

🖥️ Output

5 8

x++ returns 3 and makes x 4; ++x then makes x 5 and returns 5. So y = 3 + 5 = 8 and x is 5.

Q3. Use the remainder operator to print Fizz for multiples of 3 between 1 and 10, and the number otherwise.

Show answer

📄 practice3.js

for (let n = 1; n <= 10; n++) {
  console.log(n % 3 === 0 ? "Fizz" : n);
}

🖥️ Output

1
2
Fizz
4
5
Fizz
7
8
Fizz
10

Q4. A test passes if the status is 200 and the response time is under 2000 ms, or if the status is 304. Write the condition and test it with (200, 1500), (200, 2500) and (304, 3000).

Show answer

📄 practice4.js

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

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

🖥️ Output

true
false
true

The parentheses are not strictly needed (&& has higher precedence than ||) but make the intent clear.

Q5. Use a ternary to print 1 test failed or N tests failed for 1 and 4 failures.

Show answer

📄 practice5.js

for (const failed of [1, 4]) {
  console.log(`${failed} ${failed === 1 ? "test" : "tests"} failed`);
}

🖥️ Output

1 test failed
4 tests failed

Q6. Check whether the object { id: 7, email: undefined } has an email property and a phone property, using in. Then explain why user.email !== undefined gives a different answer.

Show answer

📄 practice6.js

const user = { id: 7, email: undefined };
console.log("email" in user, "phone" in user);
console.log(user.email !== undefined);

🖥️ Output

true false
false

in checks whether the property exists. email exists but holds undefined, so comparing its value says “no value”, while in says “the key is there”.


🧠 MCQ Quiz: Operators

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

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

💼 Interview Questions and Answers

Q1. What is the difference between x++ and ++x?

Both add 1 to x. Postfix x++ evaluates to the value before the increment; prefix ++x evaluates to the value after. The difference only matters when the expression’s value is used, for example const y = x++. As a standalone statement they are identical.

Q2. What is short-circuit evaluation, and how is it used?

&& stops at the first falsy operand and || stops at the first truthy operand, without evaluating the rest. It is used for guards (user && user.name), defaults (name || "guest", better ?? when 0 or “” are valid), and to avoid unnecessary work. It also means function calls on the right side may never run, which matters if they have side effects.

Q3. Do && and || always return booleans?

No. They return one of their operands. "a" && 0 returns 0; null || "x" returns "x". Only ! always returns a boolean. Use Boolean(a && b) or !!(a && b) when you need a real boolean, for example for an API flag.

📄 returns.js

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

⌨️ Terminal

node returns.js

🖥️ Output

0 x true

Q4. When would you use the ternary operator instead of if/else?

When choosing between two values in an expression: a label, a plural form, a default inside a template literal or JSX. Use if/else when you need to run statements (several lines, side effects) or when there are more than two branches. Nested ternaries hurt readability and are often blocked by lint rules.

Q5. What is operator precedence and associativity? Give an example where it causes a bug.

Precedence decides which operator binds first; associativity decides the order for operators of equal precedence. A common bug: "Total: " + price + tax joins strings left to right, giving "Total: 10020" instead of "Total: 120". Grouping fixes it: "Total: " + (price + tax), or use a template literal `Total: ${price + tax}`.

📄 precedence-bug.js

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

⌨️ Terminal

node precedence-bug.js

🖥️ Output

Total: 10020
Total: 120

❓ Frequently Asked Questions

🤔 What are the types of operators in JavaScript?

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

🤔 What does the % operator do in JavaScript?

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

🤔 Is there an integer division operator?

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

🤔 What is the ?: operator called?

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


🏁 Summary

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

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

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in