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.
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
Use
When
obj.key
The 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.
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:
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).
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:
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
Check
True when
obj.key !== undefined
The key exists with a value other than undefined
"key" in obj
The 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));
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.
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:
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".
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.
How do you read a property whose name is stored in a variable key?
Answer: obj[key]. obj.key looks for a property literally named “key”.
What does reading a missing property return?
Answer: undefined. Only reading a property of undefined throws.
Which is required for the key "order-id"?
Answer: Bracket notation: obj[“order-id”]. obj.order-id would be parsed as obj.order minus id.
What does { name } mean when a variable name exists?
Answer: { name: name } (shorthand property). Shorthand properties use the variable’s name as the key.
What does delete obj.key do?
Answer: Removes the property from the object. After delete, “key” in obj is false.
What is { a: 1 } === { a: 1 }?
Answer: false. Objects are compared by reference.
Which check returns true only for the object’s own property, not inherited ones?
Answer: Object.hasOwn(obj, “key”). in also finds inherited properties such as toString.
What does Object.entries({ a: 1, b: 2 }) return?
Answer: [[“a”, 1], [“b”, 2]]. Each entry is a [key, value] pair.
Inside a method called as cart.total(), what is this?
Answer: cart. this is the object before the dot.
Why can you change properties of an object declared with const?
Answer: const only prevents reassigning the variable. Use Object.freeze to prevent changes.
💼 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.
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).
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
⚠️ 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.
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.
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
Goal
Method
Mutates?
Add / remove at end
push / pop
Yes
Add / remove at start
unshift / shift
Yes
Insert / remove / replace in the middle
splice (or toSpliced)
Yes (No)
Copy part
slice
No
Join arrays
concat, [...a, ...b]
No
Array to text
join
No
Is the value there? Where?
includes, indexOf, lastIndexOf
No
Reverse
reverse (or toReversed)
Yes (No)
Sort
sort (or toSorted)
Yes (No)
Replace one item
arr[i] = x (or with)
Yes (No)
Flatten nested arrays
flat, flatMap
No
Transform / select / combine
map, 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:
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
Which method does NOT change the original array?
Answer: slice. slice returns a new array.
What does splice return?
Answer: An array of the removed items. The original array is changed in place.
What is [1, 2, 3, 4].slice(1, 3)?
Answer: [2, 3]. End index 3 is not included.
What does arr.splice(-1, 1) do?
Answer: Removes the last item. Negative start counts from the end; this is why splice(indexOf(x), 1) with -1 is a bug.
Which ES2023 method sorts without mutating?
Answer: toSorted. toReversed, toSpliced and with were added at the same time.
What is [[1, 2], [3, [4]]].flat()?
Answer: [1, 2, 3, [4]]. flat() flattens one level by default.
What does [NaN].includes(NaN) return?
Answer: true. includes uses SameValueZero, which treats NaN as equal; indexOf does not.
What is wrong with new Array(3).fill({})?
Answer: All slots hold the same object. Use Array.from({ length: 3 }, () => ({})).
What does ["a", "b"].join("") return?
Answer: “ab”. The separator is an empty string.
What does [5, 1].sort() === original tell you?
Answer: sort returns the same (mutated) array. sort sorts in place and returns the same reference.
💼 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.
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.
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:
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
Escape
Meaning
\n
New line
\t
Tab
\\
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.
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:
"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);
=== 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);
💡 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 });
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".
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.
What is "JavaScript".length?
Answer: 10. Count every character: J-a-v-a-S-c-r-i-p-t.
What does "tester".at(-1) return?
Answer: “r”. at() with -1 returns the last character.
After let s = "abc"; s.toUpperCase(); what is s?
Answer: “abc”. Strings are immutable; the result was not stored.
What does "2026-11-23".slice(5, 7) return?
Answer: “11”. slice includes the start index and excludes the end index.
What does "a,b,c".split(",") return?
Answer: [“a”, “b”, “c”]. split returns an array of pieces.
What does "1,000,000".replace(",", "") return?
Answer: “1000,000”. With a string pattern, replace changes only the first match; use replaceAll or a /g regex.
Which method checks whether a string begins with “https”?
Answer: startsWith. There is no beginsWith method.
What does "QA".indexOf("x") return?
Answer: -1. indexOf returns -1 when the text is not found.
What does "7".padStart(3, "0") return?
Answer: “007”. It pads at the start until the length is 3.
Why can "👍".length be 2?
Answer: Some characters use two UTF-16 code units. Use […str].length to count code points.
💼 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.
👉 Answer: Reference to original repository (especially in forks).
👉 Use Case: Keep your fork updated with original repo.
Mock Interview: GitHub (Real Company Style)
🔹 Round 1: Basics + Practical Understanding
❓ Q1: Explain your GitHub workflow in your current project.
👉 Strong Answer:
“We follow a feature branch workflow. Each task starts with a new branch from main. After development, we push code and raise a pull request. CI runs automatically using GitHub Actions. After code review and approvals, we merge into main. Direct commits to main are restricted.”
👉 What interviewer checks:
Real experience
Collaboration understanding
CI/CD awareness
❓ Q2: What happens when you run git push?
👉 Strong Answer:
“It uploads local commits from my machine (using Git) to the remote repository on GitHub, making them available to the team.”
👉 Follow-up trap: 👉 “What if push is rejected?”
✔️ Answer:
“It usually means my branch is behind. I pull the latest changes, resolve conflicts if any, and push again.”
🔹 Round 2: Scenario-Based Questions
❓ Q3: You and another developer changed the same file. Your PR shows conflict. What do you do?
👉 Strong Answer:
“I pull the latest changes from main, resolve conflicts locally, test the code, commit the fix, and push again to update the PR.”
👉 Bonus point: Mention testing after conflict resolution.
❓ Q4: You accidentally pushed sensitive data (API key) to GitHub. What will you do?
👉 Strong Answer:
“First, I revoke the key immediately. Then I remove it from the repository, rewrite history if needed, and ensure it’s added to .gitignore. Going forward, I store secrets using GitHub Secrets.”
👉 What interviewer checks:
Security awareness
Real-world handling
❓ Q5: Your teammate’s PR broke the build. What should happen?
👉 Strong Answer:
“The CI pipeline should fail automatically. The PR should not be merged until the issue is fixed. We enforce required checks before merging.”
👉 Extra credit: Mention branch protection rules.
🔹 Round 3: CI/CD + Automation (Very Important)
❓ Q6: How do you integrate automation tests with GitHub?
👉 Strong Answer:
“We use GitHub Actions to trigger Playwright tests on every PR. The workflow installs dependencies, runs tests, and publishes reports.”
👉 Example flow:
PR created
Tests run automatically
Pass → merge allowed
Fail → fix required
❓ Q7: How do you ensure code quality before merging?
👉 Strong Answer:
“We use a combination of:
Pull request reviews
Automated tests
Linting checks
CI validation
Only after all checks pass, the PR is merged.”
🔹 Round 4: Advanced Problem Solving
❓ Q8: Your main branch is broken after a merge. What will you do?
👉 Strong Answer:
“I would quickly identify the faulty commit and revert it using git revert. Then fix the issue in a new branch and raise another PR.”
👉 Important: Avoid rewriting history in shared branches.
❓ Q9: How do you handle multiple environments (dev, staging, prod)?
👉 Strong Answer:
“We use different branches or deployment workflows. For example:
develop → dev environment
main → production CI/CD pipelines deploy automatically based on branch.”
❓ Q10: How do you manage large teams working on the same repo?
👉 Strong Answer:
“We use:
Feature branches
Clear naming conventions
Code owners
Mandatory PR reviews
CI/CD checks
This ensures smooth collaboration and avoids conflicts.”
🔹 Round 5: Rapid Fire (Quick Checks)
❓ Difference between Fork and Clone?
👉 Fork = copy on GitHub 👉 Clone = copy on local machine
❓ What is HEAD in Git?
👉 Pointer to the current commit/branch
❓ What is Rebase?
👉 Rewrites commit history to make it linear
❓ What is Stash?
👉 Temporarily saves uncommitted changes
❓ What is a Tag?
👉 Marks a release/version
🔹 Real Interview Challenge (Hands-On Thinking)
❓ Q11: Design a GitHub workflow for automation testing.
👉 Strong Answer:
“I would:
Trigger workflow on PR and push
Install dependencies
Run Playwright tests
Generate reports
Upload artifacts
Fail build if tests fail
This ensures only tested code gets merged.”
🔹 Final HR + Practical Question
❓ Q12: Tell me a real problem you faced in GitHub and how you solved it.
👉 Sample Answer:
“We had frequent merge conflicts due to long-running branches. I suggested smaller PRs and frequent rebasing. This reduced conflicts and improved deployment speed.”
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`);
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
Declaration
Expression
Syntax
function name() {}
const name = function () {};
Hoisted with body
Yes
No
Can be anonymous
No
Yes
Typical use
Top-level helpers
Callbacks, 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.
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.
What does a function return if it has no return statement?
Answer:undefined. Without return, a function returns undefined.
In function add(a, b) {} and add(2, 3), what are 2 and 3?
Answer: Arguments. Parameters are the names in the definition; arguments are the values passed in a call.
What is the value of a parameter when no argument is passed?
Answer:undefined. Missing arguments become undefined unless a default is given.
Which can be called before the line where it is defined?
Answer: A function declaration. Function declarations are hoisted together with their body.
What happens to code after a return statement in the same block?
Answer: It never runs. return ends the function immediately.
Which describes a pure function?
Answer: Same input always gives the same output, with no side effects. Pure functions do not read or change outside state.
What is the result?
function f(obj) { obj.n = 2; }
const o = { n: 1 };
f(o);
console.log(o.n);
Answer: 2. The parameter refers to the same object as o.
How can a function return two values?
Answer: Return an object or an array. return a, b uses the comma operator and returns only b.
Which name best follows conventions for a function that checks a login state?
Answer:isLoggedIn. Boolean-returning functions usually start with is/has/can, in camelCase.
What does typeof function () {} return?
Answer:"function". Functions are objects, but typeof reports them as “function”.
💼 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.
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.