JavaScript Object Practice Programs with Solutions (32 Programs)

Practise JavaScript objects with 32 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.

New to this topic? Read the JavaScript Objects lesson first.

JavaScript Beginner Programs

1. Create and read an objectBeginner

Create a user object with name, role and active, then print each property.

Show solution
const user = { name: 'Asha', role: 'tester', active: true };
console.log(user.name);
console.log(user['role']);
console.log(user.active);

Output

Asha
tester
true

Explanation: dot notation is the usual way to read properties. Bracket notation also works, and is needed for dynamic keys.

2. Add, update and delete propertiesBeginner

Add an email, change the role and delete active from a user object.

Show solution
const user = { name: 'Asha', role: 'tester', active: true };
user.email = 'asha@test.com';
user.role = 'lead';
delete user.active;
console.log(user);

Output

{ name: 'Asha', role: 'lead', email: 'asha@test.com' }

Explanation: objects are mutable, so properties can be added, changed or removed after creation.

3. Dynamic property namesBeginner

Read a property whose name is stored in a variable.

Show solution
const settings = { browser: 'chromium', retries: 2 };
const key = 'retries';
console.log(settings[key]);
console.log(settings.key);

Output

2
undefined

Explanation: settings[key] uses the variable’s value. settings.key looks for a property literally called key.

4. Check whether a property existsBeginner

Check for retries and proxy with in and Object.hasOwn.

Show solution
const config = { retries: 0 };
console.log('retries' in config);
console.log(Object.hasOwn(config, 'proxy'));
console.log(config.retries !== undefined);

Output

true
false
true

Explanation: in and Object.hasOwn check existence even when the value is falsy, such as 0.

5. Keys, values and entriesBeginner

Print the keys, values and entries of a test-case object.

Show solution
const testCase = { id: 'TC-1', priority: 'high', automated: true };
console.log(Object.keys(testCase));
console.log(Object.values(testCase));
console.log(Object.entries(testCase).length);

Output

[ 'id', 'priority', 'automated' ]
[ 'TC-1', 'high', true ]
3

Explanation: these methods turn an object into arrays that you can loop over or transform.

6. Loop over an objectBeginner

Print each property of a config object as key: value.

Show solution
const config = { browser: 'firefox', headless: false, workers: 2 };
for (const [key, value] of Object.entries(config)) {
  console.log(`${key}: ${value}`);
}

Output

browser: firefox
headless: false
workers: 2

Explanation: Object.entries with for...of and destructuring gives both key and value on each pass.

7. Object with a methodBeginner

Create a calculator object with add and subtract methods.

Show solution
const calculator = {
  add(a, b) { return a + b; },
  subtract(a, b) { return a - b; }
};
console.log(calculator.add(10, 5));
console.log(calculator.subtract(10, 5));

Output

15
5

Explanation: functions stored on an object are called methods.

8. Using this in a methodBeginner

Create a user object whose describe method uses this.

Show solution
const user = {
  name: 'Ravi',
  role: 'admin',
  describe() {
    return `${this.name} is an ${this.role}`;
  }
};
console.log(user.describe());

Output

Ravi is an admin

Explanation: inside a regular method, this refers to the object the method was called on.

9. Shorthand propertiesBeginner

Build an object from variables using shorthand property names.

Show solution
const browser = 'webkit';
const viewport = '1280x720';
const project = { browser, viewport };
console.log(project);

Output

{ browser: 'webkit', viewport: '1280x720' }

Explanation: { browser } is shorthand for { browser: browser } when the variable and property share a name.

10. Nested objectsBeginner

Read nested properties from an order object.

Show solution
const order = { id: 501, customer: { name: 'Meera', address: { city: 'Pune' } } };
console.log(order.customer.name);
console.log(order.customer.address.city);

Output

Meera
Pune

Explanation: chain property access to reach nested values.

JavaScript Intermediate Programs

11. Object destructuring with defaultsIntermediate

Destructure an options object with defaults and a renamed property.

Show solution
const options = { timeout: 5000, headless: false };
const { timeout, headless = true, retries = 1, timeout: waitMs } = options;
console.log(timeout, headless, retries, waitMs);

Output

5000 false 1 5000

Explanation: defaults apply only when a property is undefined. timeout: waitMs copies the same value into a new name.

12. Merge objects with spreadIntermediate

Merge default settings with overrides, keeping the overrides.

Show solution
const defaults = { browser: 'chromium', retries: 0, video: 'off' };
const overrides = { retries: 2, video: 'on' };
const merged = { ...defaults, ...overrides };
console.log(merged);

Output

{ browser: 'chromium', retries: 2, video: 'on' }

Explanation: later spreads overwrite earlier properties with the same name.

13. Shallow vs deep copyIntermediate

Show that a spread copy shares nested objects, and fix it with structuredClone.

Show solution
const original = { name: 'cart', items: ['pen'] };
const shallow = { ...original };
const deep = structuredClone(original);
shallow.items.push('book');
deep.items.push('bag');
console.log(original.items);
console.log(deep.items);

Output

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

Explanation: spread copies only the top level. structuredClone copies nested data too.

14. Freeze and sealIntermediate

Compare Object.freeze and Object.seal.

Show solution
const frozen = Object.freeze({ env: 'qa' });
const sealed = Object.seal({ env: 'qa' });
frozen.env = 'prod';
sealed.env = 'prod';
sealed.extra = true;
console.log(frozen.env, sealed.env, 'extra' in sealed);

Output

qa prod false

Explanation: frozen objects cannot change at all. Sealed objects allow value changes but no new or deleted properties.

15. Count propertiesIntermediate

Count how many properties an object has.

Show solution
const response = { id: 1, name: 'Item', price: 99, inStock: true };
console.log(Object.keys(response).length);

Output

4

Explanation: objects have no length, so count their keys instead.

16. Transform an objectIntermediate

Apply a 10% discount to every price in a price list object.

Show solution
const prices = { pen: 20, book: 350, bag: 900 };
const discounted = Object.fromEntries(
  Object.entries(prices).map(([item, price]) => [item, price * 0.9])
);
console.log(discounted);

Output

{ pen: 18, book: 315, bag: 810 }

Explanation: convert to entries, map them, and convert back with Object.fromEntries.

17. Filter object propertiesIntermediate

Keep only the settings whose values are not null.

Show solution
const settings = { browser: 'chromium', proxy: null, retries: 2, baseURL: null };
const cleaned = Object.fromEntries(Object.entries(settings).filter(([, value]) => value !== null));
console.log(cleaned);

Output

{ browser: 'chromium', retries: 2 }

Explanation: filtering entries is the object equivalent of array.filter.

18. Compare two objectsIntermediate

Write a function that checks whether two flat objects have the same keys and values.

Show solution
function shallowEqual(a, b) {
  const keysA = Object.keys(a);
  const keysB = Object.keys(b);
  if (keysA.length !== keysB.length) return false;
  return keysA.every(key => a[key] === b[key]);
}
console.log(shallowEqual({ x: 1, y: 2 }, { y: 2, x: 1 }));
console.log(shallowEqual({ x: 1 }, { x: '1' }));

Output

true
false

Explanation: === compares object references, so content equality needs a key-by-key check.

19. Getters and settersIntermediate

Create an object with a fullName getter and setter.

Show solution
const person = {
  first: 'Asha',
  last: 'Sharma',
  get fullName() { return `${this.first} ${this.last}`; },
  set fullName(value) { [this.first, this.last] = value.split(' '); }
};
console.log(person.fullName);
person.fullName = 'Neha Verma';
console.log(person.first, person.last);

Output

Asha Sharma
Neha Verma

Explanation: getters and setters run code when a property is read or written, while looking like normal properties.

20. Optional chaining on missing dataIntermediate

Read a deeply nested value that may not exist.

Show solution
const responses = [
  { data: { user: { profile: { country: 'IN' } } } },
  { data: { user: null } },
  {}
];
for (const r of responses) console.log(r.data?.user?.profile?.country ?? 'unknown');

Output

IN
unknown
unknown

Explanation: ?. stops at the first null or undefined, so missing data never throws.

JavaScript Real-World QA Scenario Programs

21. Validate an API responseReal-world

Check that an API user object has all required fields with the right types.

Show solution
const required = { id: 'number', email: 'string', active: 'boolean' };
const user = { id: 12, email: 'qa@test.com', active: 'true' };
const problems = Object.entries(required)
  .filter(([field, type]) => typeof user[field] !== type)
  .map(([field, type]) => `${field} should be ${type}`);
console.log(problems.length ? problems.join('; ') : 'Response is valid');

Output

active should be boolean

Explanation: a small schema object lets one loop check every field, a lightweight contract test.

22. Build test data with defaultsReal-world

Write buildUser(overrides) that returns a default user merged with overrides.

Show solution
function buildUser(overrides = {}) {
  return { name: 'QA User', email: 'qa.user@example.com', role: 'viewer', active: true, ...overrides };
}
console.log(buildUser().role);
const admin = buildUser({ role: 'admin', name: 'Admin' });
console.log(admin.name, admin.role, admin.active);

Output

viewer
Admin admin true

Explanation: a data builder gives sensible defaults, and each test overrides only what it needs.

23. Count tests by statusReal-world

Use an object to count statuses in a results array.

Show solution
const statuses = ['passed', 'failed', 'passed', 'flaky', 'passed', 'failed'];
const counts = {};
for (const s of statuses) counts[s] = (counts[s] ?? 0) + 1;
console.log(counts);

Output

{ passed: 3, failed: 2, flaky: 1 }

Explanation: object keys work as counters, a pattern used in every test report.

24. Environment config lookupReal-world

Store base URLs per environment in an object and pick one by name.

Show solution
const environments = {
  qa: { baseURL: 'https://qa.shop.test', retries: 1 },
  staging: { baseURL: 'https://staging.shop.test', retries: 2 }
};
const envName = 'staging';
const env = environments[envName] ?? environments.qa;
console.log(env.baseURL, env.retries);

Output

https://staging.shop.test 2

Explanation: an object lookup replaces a chain of if statements and falls back to a default.

25. Map API fields to UI labelsReal-world

Rename snake_case API keys to readable labels.

Show solution
const apiUser = { first_name: 'Ravi', last_name: 'Kumar', phone_no: '9876543210' };
const labels = { first_name: 'First name', last_name: 'Last name', phone_no: 'Phone' };
for (const [key, value] of Object.entries(apiUser)) {
  console.log(`${labels[key]}: ${value}`);
}

Output

First name: Ravi
Last name: Kumar
Phone: 9876543210

Explanation: a mapping object keeps label translations in one place.

26. Diff expected vs actual objectsReal-world

Report which fields differ between expected and actual user details.

Show solution
const expected = { name: 'Asha', city: 'Delhi', plan: 'pro' };
const actual = { name: 'Asha', city: 'Mumbai', plan: 'free' };
for (const key of Object.keys(expected)) {
  if (expected[key] !== actual[key]) {
    console.log(`${key}: expected '${expected[key]}', got '${actual[key]}'`);
  }
}

Output

city: expected 'Delhi', got 'Mumbai'
plan: expected 'pro', got 'free'

Explanation: field-level differences make failed assertions much easier to understand than a plain false.

27. Group products by categoryReal-world

Group product names under their category.

Show solution
const products = [
  { name: 'Mouse', category: 'electronics' },
  { name: 'Pen', category: 'stationery' },
  { name: 'Keyboard', category: 'electronics' }
];
const groups = {};
for (const p of products) (groups[p.category] ??= []).push(p.name);
console.log(groups);

Output

{ electronics: [ 'Mouse', 'Keyboard' ], stationery: [ 'Pen' ] }

Explanation: ??= creates the array the first time a category appears, then each product is pushed into it.

28. Read headers case-insensitivelyReal-world

Find the Content-Type header regardless of letter case.

Show solution
const headers = { 'content-type': 'application/json', 'X-Request-Id': 'abc-1' };
function getHeader(all, name) {
  const key = Object.keys(all).find(k => k.toLowerCase() === name.toLowerCase());
  return key ? all[key] : undefined;
}
console.log(getHeader(headers, 'Content-Type'));
console.log(getHeader(headers, 'x-request-id'));

Output

application/json
abc-1

Explanation: HTTP header names are case-insensitive, so compare them in lower case.

29. Remove sensitive fields before loggingReal-world

Copy a user object without its password and token before printing it.

Show solution
const user = { id: 3, email: 'qa@test.com', password: 'Secret!23', token: 'abc.def' };
const { password, token, ...safeUser } = user;
console.log(safeUser);

Output

{ id: 3, email: 'qa@test.com' }

Explanation: rest destructuring collects every property except the named ones, a quick way to strip secrets.

30. Convert form data to a query stringReal-world

Turn a filter object into a URL query string, skipping empty values.

Show solution
const filters = { q: 'laptop', minPrice: 30000, brand: '', sort: 'price_asc' };
const params = new URLSearchParams(
  Object.entries(filters).filter(([, v]) => v !== '').map(([k, v]) => [k, String(v)])
);
console.log(params.toString());

Output

q=laptop&minPrice=30000&sort=price_asc

Explanation: filter out empty values, then URLSearchParams handles encoding.

31. Track a page object’s stateReal-world

Create a cart object with methods that add items and calculate the total.

Show solution
const cart = {
  items: [],
  add(name, price, qty = 1) { this.items.push({ name, price, qty }); return this; },
  total() { return this.items.reduce((sum, i) => sum + i.price * i.qty, 0); }
};
cart.add('Mouse', 599).add('Cable', 199, 2);
console.log(cart.items.length, 'items, total', cart.total());

Output

2 items, total 997

Explanation: methods share state through this, and returning this allows chaining calls.

32. Convert an array of rows into objectsReal-world

Convert CSV rows into objects using the header row as keys.

Show solution
const rows = [['id', 'user', 'status'], ['1', 'asha', 'active'], ['2', 'ravi', 'locked']];
const [header, ...data] = rows;
const records = data.map(row => Object.fromEntries(header.map((h, i) => [h, row[i]])));
console.log(records[1]);
console.log(records.length);

Output

{ id: '2', user: 'ravi', status: 'locked' }
2

Explanation: pairing each header with the value at the same index builds one object per row.

Keep Practising

JavaScript Array Practice Programs with Solutions (33 Programs)

Practise JavaScript arrays with 33 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.

New to this topic? Read the JavaScript Array Methods lesson first.

JavaScript Beginner Programs

1. Create and read an arrayBeginner

Create an array of three browsers and print the first, last and length.

Show solution
const browsers = ['chromium', 'firefox', 'webkit'];
console.log(browsers[0]);
console.log(browsers[browsers.length - 1]);
console.log(browsers.length);

Output

chromium
webkit
3

Explanation: array indexes start at 0, so the last item is at length - 1.

2. Add and remove at the endBeginner

Use push and pop on a list of test names.

Show solution
const tests = ['login', 'search'];
tests.push('checkout');
console.log(tests);
const last = tests.pop();
console.log('Removed:', last, '| Now:', tests);

Output

[ 'login', 'search', 'checkout' ]
Removed: checkout | Now: [ 'login', 'search' ]

Explanation: push adds to the end and pop removes and returns the last item.

3. Add and remove at the startBeginner

Use unshift and shift on a queue of jobs.

Show solution
const queue = ['build', 'test'];
queue.unshift('install');
console.log(queue);
const first = queue.shift();
console.log('Processing:', first, '| Remaining:', queue);

Output

[ 'install', 'build', 'test' ]
Processing: install | Remaining: [ 'build', 'test' ]

Explanation: unshift adds to the front and shift removes the first item, which is how a queue works.

4. Check if an item existsBeginner

Check whether 'firefox' and 'edge' are in the browser list.

Show solution
const browsers = ['chromium', 'firefox', 'webkit'];
console.log(browsers.includes('firefox'));
console.log(browsers.includes('edge'));
console.log(browsers.indexOf('webkit'));

Output

true
false
2

Explanation: includes returns a boolean. indexOf returns the position, or -1 if missing.

5. Double every number with mapBeginner

Double each value in [1, 2, 3, 4].

Show solution
const values = [1, 2, 3, 4];
const doubled = values.map(v => v * 2);
console.log(doubled);
console.log(values);

Output

[ 2, 4, 6, 8 ]
[ 1, 2, 3, 4 ]

Explanation: map returns a new array with each item transformed. The original array is unchanged.

6. Filter even numbersBeginner

Keep only the even numbers from [3, 8, 12, 5, 6].

Show solution
const evens = [3, 8, 12, 5, 6].filter(n => n % 2 === 0);
console.log(evens);

Output

[ 8, 12, 6 ]

Explanation: filter keeps items for which the callback returns true.

7. Sum with reduceBeginner

Add up [120, 80, 45, 55].

Show solution
const total = [120, 80, 45, 55].reduce((sum, n) => sum + n, 0);
console.log(total);

Output

300

Explanation: reduce combines all items into one value, starting from the initial value 0.

8. Join an array into a stringBeginner

Join tags with ', ' and with ' | '.

Show solution
const tags = ['smoke', 'regression', 'api'];
console.log(tags.join(', '));
console.log(tags.join(' | '));

Output

smoke, regression, api
smoke | regression | api

Explanation: join turns an array into a string with your chosen separator.

9. Slice part of an arrayBeginner

Take the first two and the last two items from a list.

Show solution
const steps = ['open', 'login', 'search', 'add to cart', 'checkout'];
console.log(steps.slice(0, 2));
console.log(steps.slice(-2));

Output

[ 'open', 'login' ]
[ 'add to cart', 'checkout' ]

Explanation: slice returns a copy of part of the array without changing the original.

10. Loop with forEachBeginner

Print each item with its index using forEach.

Show solution
const steps = ['open page', 'fill form', 'submit'];
steps.forEach((step, index) => console.log(`${index + 1}. ${step}`));

Output

1. open page
2. fill form
3. submit

Explanation: forEach runs a callback for every item. Use for...of instead when you need await or break.

JavaScript Intermediate Programs

11. Find an itemIntermediate

Find the first user with the role 'admin'.

Show solution
const users = [
  { name: 'Asha', role: 'viewer' },
  { name: 'Ravi', role: 'admin' },
  { name: 'Meera', role: 'admin' }
];
const admin = users.find(u => u.role === 'admin');
console.log(admin.name);
console.log(users.findIndex(u => u.role === 'admin'));

Output

Ravi
1

Explanation: find returns the first matching item and findIndex returns its position.

12. some and everyIntermediate

Check whether some tests failed and whether every test passed.

Show solution
const results = ['passed', 'passed', 'failed'];
console.log('Any failed:', results.some(r => r === 'failed'));
console.log('All passed:', results.every(r => r === 'passed'));

Output

Any failed: true
All passed: false

Explanation: some needs one match, every needs all items to match. Both stop early when the answer is known.

13. Sort numbers correctlyIntermediate

Sort [10, 1, 25, 3] ascending and descending.

Show solution
const values = [10, 1, 25, 3];
console.log([...values].sort());
console.log([...values].sort((a, b) => a - b));
console.log([...values].sort((a, b) => b - a));

Output

[ 1, 10, 25, 3 ]
[ 1, 3, 10, 25 ]
[ 25, 10, 3, 1 ]

Explanation: the default sort compares as strings, so 10 comes before 3. Pass a compare function for numbers. Spreading copies first, because sort changes the array in place.

14. Sort objects by a propertyIntermediate

Sort products by price, then print their names.

Show solution
const products = [
  { name: 'Mouse', price: 599 },
  { name: 'Keyboard', price: 1499 },
  { name: 'Cable', price: 199 }
];
const byPrice = [...products].sort((a, b) => a.price - b.price);
console.log(byPrice.map(p => p.name).join(' < '));

Output

Cable < Mouse < Keyboard

Explanation: the compare function reads the property you want to sort by.

15. Remove duplicatesIntermediate

Remove duplicate tags from ['ui', 'api', 'ui', 'smoke', 'api'].

Show solution
const tags = ['ui', 'api', 'ui', 'smoke', 'api'];
const unique = [...new Set(tags)];
console.log(unique);

Output

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

Explanation: a Set keeps only unique values. Spreading it back gives an array.

16. Flatten nested arraysIntermediate

Flatten [[1, 2], [3, [4, 5]]] one level and fully.

Show solution
const nested = [[1, 2], [3, [4, 5]]];
console.log(nested.flat());
console.log(nested.flat(Infinity));

Output

[ 1, 2, 3, [ 4, 5 ] ]
[ 1, 2, 3, 4, 5 ]

Explanation: flat(depth) removes nesting. Infinity flattens every level.

17. Chain map, filter and reduceIntermediate

Calculate the total price of in-stock items only.

Show solution
const items = [
  { name: 'Pen', price: 20, inStock: true },
  { name: 'Book', price: 350, inStock: false },
  { name: 'Bag', price: 899, inStock: true }
];
const total = items
  .filter(i => i.inStock)
  .map(i => i.price)
  .reduce((sum, p) => sum + p, 0);
console.log(total);

Output

919

Explanation: chaining small steps keeps each transformation simple and readable.

18. splice to insert and removeIntermediate

Insert 'verify email' at position 2 and remove 'logout'.

Show solution
const steps = ['register', 'login', 'logout', 'delete account'];
steps.splice(2, 0, 'verify email');
console.log(steps);
steps.splice(steps.indexOf('logout'), 1);
console.log(steps);

Output

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

Explanation: splice(start, deleteCount, ...items) changes the array in place. It can remove and insert in one call.

19. Array destructuringIntermediate

Unpack the first item, the second item and the rest from a results array.

Show solution
const scores = [98, 87, 75, 60, 42];
const [top, second, ...others] = scores;
console.log(top, second);
console.log(others);

Output

98 87
[ 75, 60, 42 ]

Explanation: destructuring assigns array items to variables by position, and ...rest collects the remainder.

20. Group items by a keyIntermediate

Group tests by their status.

Show solution
const tests = [
  { id: 1, status: 'passed' }, { id: 2, status: 'failed' },
  { id: 3, status: 'passed' }, { id: 4, status: 'skipped' }
];
const groups = tests.reduce((acc, t) => {
  (acc[t.status] ||= []).push(t.id);
  return acc;
}, {});
console.log(groups);

Output

{ passed: [ 1, 3 ], failed: [ 2 ], skipped: [ 4 ] }

Explanation: reduce builds an object whose keys are statuses and whose values are arrays of IDs.

JavaScript Real-World QA Scenario Programs

21. Verify a list is sortedReal-world

Check whether prices read from the UI are sorted from low to high.

Show solution
const uiPrices = [199, 599, 599, 1499];
const isSorted = uiPrices.every((p, i) => i === 0 || uiPrices[i - 1] <= p);
console.log('Sorted ascending:', isSorted);
const expected = [...uiPrices].sort((a, b) => a - b);
console.log(JSON.stringify(uiPrices) === JSON.stringify(expected));

Output

Sorted ascending: true
true

Explanation: two common checks are comparing neighbours with every, or comparing with a sorted copy.

22. Compare expected and actual menu itemsReal-world

Find items that are missing from the UI and unexpected extras.

Show solution
const expected = ['Home', 'Shop', 'Blog', 'Contact'];
const actual = ['Home', 'Shop', 'Offers', 'Contact'];
const missing = expected.filter(x => !actual.includes(x));
const extra = actual.filter(x => !expected.includes(x));
console.log('Missing:', missing);
console.log('Extra:', extra);

Output

Missing: [ 'Blog' ]
Extra: [ 'Offers' ]

Explanation: two filters give a clear diff, which is easier to debug than a single equality check.

23. Count failed tests per browserReal-world

Count failures for each browser from a list of results.

Show solution
const results = [
  { browser: 'chromium', status: 'failed' },
  { browser: 'firefox', status: 'passed' },
  { browser: 'webkit', status: 'failed' },
  { browser: 'chromium', status: 'failed' }
];
const failures = {};
for (const r of results.filter(r => r.status === 'failed')) {
  failures[r.browser] = (failures[r.browser] || 0) + 1;
}
console.log(failures);

Output

{ chromium: 2, webkit: 1 }

Explanation: filter first, then count, keeping each step simple.

24. Top 3 slowest testsReal-world

Find the three slowest tests by duration.

Show solution
const durations = [
  { name: 'login', ms: 1200 }, { name: 'search', ms: 4300 },
  { name: 'checkout', ms: 8700 }, { name: 'profile', ms: 900 }, { name: 'cart', ms: 5100 }
];
const slowest = [...durations].sort((a, b) => b.ms - a.ms).slice(0, 3);
for (const t of slowest) console.log(`${t.name}: ${t.ms} ms`);

Output

checkout: 8700 ms
cart: 5100 ms
search: 4300 ms

Explanation: sort a copy in descending order, then slice the first three.

25. Paginate an arrayReal-world

Split 7 items into pages of 3 and print page 3.

Show solution
const items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const pageSize = 3;
const page = n => items.slice((n - 1) * pageSize, n * pageSize);
console.log(page(1));
console.log(page(3));
console.log('Pages:', Math.ceil(items.length / pageSize));

Output

[ 'a', 'b', 'c' ]
[ 'g' ]
Pages: 3

Explanation: slice with start and end indexes calculated from the page number gives each page.

26. Chunk test cases for parallel workersReal-world

Split 10 test IDs into chunks for 3 workers.

Show solution
const tests = Array.from({ length: 10 }, (_, i) => `TC${i + 1}`);
const workers = 3;
const chunks = Array.from({ length: workers }, () => []);
tests.forEach((t, i) => chunks[i % workers].push(t));
chunks.forEach((c, i) => console.log(`Worker ${i + 1}: ${c.join(', ')}`));

Output

Worker 1: TC1, TC4, TC7, TC10
Worker 2: TC2, TC5, TC8
Worker 3: TC3, TC6, TC9

Explanation: distributing with i % workers balances the work, similar to how test runners spread tests.

27. Build a lookup from an arrayReal-world

Turn an array of users into an object keyed by ID.

Show solution
const users = [{ id: 7, name: 'Asha' }, { id: 9, name: 'Ravi' }];
const byId = Object.fromEntries(users.map(u => [u.id, u.name]));
console.log(byId);
console.log(byId[9]);

Output

{ '7': 'Asha', '9': 'Ravi' }
Ravi

Explanation: a lookup object gives fast access by key instead of searching the array each time.

28. Table data: average of a columnReal-world

Calculate the average price from table rows read as text.

Show solution
const rows = [
  ['Mouse', '₹599'],
  ['Keyboard', '₹1,499'],
  ['Cable', '₹199']
];
const prices = rows.map(([, price]) => Number(price.replace(/[^\d.]/g, '')));
const avg = prices.reduce((a, b) => a + b, 0) / prices.length;
console.log(prices);
console.log('Average:', avg.toFixed(2));

Output

[ 599, 1499, 199 ]
Average: 765.67

Explanation: map each row to a clean number, then reduce to the average. The leading comma in [, price] skips the first column.

29. Merge two result lists without duplicatesReal-world

Combine test IDs from two runs and keep each ID once, sorted.

Show solution
const run1 = ['TC3', 'TC1', 'TC5'];
const run2 = ['TC2', 'TC5', 'TC1'];
const all = [...new Set([...run1, ...run2])].sort();
console.log(all);

Output

[ 'TC1', 'TC2', 'TC3', 'TC5' ]

Explanation: spread both arrays into a Set to remove duplicates, then sort the result.

30. Find newly failing testsReal-world

Compare yesterday’s and today’s failures to find new ones.

Show solution
const yesterday = ['TC2', 'TC8'];
const today = ['TC2', 'TC5', 'TC9'];
const newFailures = today.filter(t => !yesterday.includes(t));
const fixed = yesterday.filter(t => !today.includes(t));
console.log('New failures:', newFailures.join(', '));
console.log('Fixed:', fixed.join(', '));

Output

New failures: TC5, TC9
Fixed: TC8

Explanation: set differences highlight regressions and fixes between runs.

31. Check all form fields are filledReal-world

Report which required fields are empty.

Show solution
const form = [
  { field: 'name', value: 'Asha' },
  { field: 'email', value: '' },
  { field: 'phone', value: '9876543210' },
  { field: 'city', value: '  ' }
];
const empty = form.filter(f => f.value.trim() === '').map(f => f.field);
console.log(empty.length ? `Empty: ${empty.join(', ')}` : 'All fields filled');

Output

Empty: email, city

Explanation: trimming first treats spaces-only values as empty, which matches most form validation rules.

32. Run async steps in orderReal-world

Run three async steps one after another and collect their results in order.

Show solution
const step = (name, ms) => new Promise(resolve => setTimeout(() => resolve(`${name} done`), ms));
const plan = [['login', 30], ['search', 10], ['logout', 20]];
const log = [];
for (const [name, ms] of plan) log.push(await step(name, ms));
console.log(log);

Output

[ 'login done', 'search done', 'logout done' ]

Explanation: for...of with await keeps the order, even though search is the fastest step. forEach would not wait.

33. Run independent requests in parallelReal-world

Run three independent async lookups in parallel with Promise.all and keep the input order.

Show solution
const fetchPrice = (sku, ms) => new Promise(resolve => setTimeout(() => resolve({ sku, price: ms * 10 }), ms));
const results = await Promise.all([fetchPrice('A1', 30), fetchPrice('B2', 10), fetchPrice('C3', 20)]);
console.log(results.map(r => `${r.sku}:${r.price}`).join(' '));

Output

A1:300 B2:100 C3:200

Explanation: Promise.all runs the work at the same time but returns results in the same order as the input array.

Keep Practising

JavaScript String Practice Programs with Solutions (32 Programs)

Practise JavaScript strings with 32 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.

New to this topic? Read the JavaScript Strings lesson first.

JavaScript Beginner Programs

1. String lengthBeginner

Print the length of 'Playwright Testing'.

Show solution
const title = 'Playwright Testing';
console.log(title.length);

Output

18

Explanation: length counts every character, including spaces.

2. Upper and lower caseBeginner

Convert 'Login Page' to upper case and lower case.

Show solution
const text = 'Login Page';
console.log(text.toUpperCase());
console.log(text.toLowerCase());

Output

LOGIN PAGE
login page

Explanation: case methods return new strings. The original string is unchanged.

3. First and last characterBeginner

Print the first and last character of 'automation'.

Show solution
const word = 'automation';
console.log(word[0]);
console.log(word.at(-1));

Output

a
n

Explanation: index 0 is the first character, and at(-1) reads from the end.

4. Trim whitespaceBeginner

Remove spaces around ' qa@example.com '.

Show solution
const raw = '   qa@example.com  ';
console.log(`[${raw.trim()}]`);
console.log(`[${raw.trimStart()}]`);

Output

[qa@example.com]
[qa@example.com  ]

Explanation: trim removes whitespace from both ends. trimStart and trimEnd remove one side only.

5. Check if a string contains textBeginner

Check whether 'Order placed successfully' contains 'success' and 'failed'.

Show solution
const message = 'Order placed successfully';
console.log(message.includes('success'));
console.log(message.includes('failed'));

Output

true
false

Explanation: includes returns true or false. It is case-sensitive.

6. startsWith and endsWithBeginner

Check whether a URL starts with https:// and ends with /login.

Show solution
const url = 'https://qa.shop.test/login';
console.log(url.startsWith('https://'));
console.log(url.endsWith('/login'));

Output

true
true

Explanation: these methods check the beginning or end of a string without regular expressions.

7. Extract part of a stringBeginner

Extract 'Play' and 'wright' from 'Playwright' with slice.

Show solution
const tool = 'Playwright';
console.log(tool.slice(0, 4));
console.log(tool.slice(4));
console.log(tool.slice(-6));

Output

Play
wright
wright

Explanation: slice(start, end) stops before end. Negative numbers count from the end.

8. Replace textBeginner

Replace 'staging' with 'qa' in a URL, then replace every space with a dash in a title.

Show solution
const url = 'https://staging.shop.test/staging/home';
console.log(url.replace('staging', 'qa'));
console.log(url.replaceAll('staging', 'qa'));
console.log('My First Test'.replaceAll(' ', '-'));

Output

https://qa.shop.test/staging/home
https://qa.shop.test/qa/home
My-First-Test

Explanation: replace changes only the first match. replaceAll changes every match.

9. Split a sentence into wordsBeginner

Split 'run tests in parallel' into words and count them.

Show solution
const sentence = 'run tests in parallel';
const words = sentence.split(' ');
console.log(words);
console.log('Word count:', words.length);

Output

[ 'run', 'tests', 'in', 'parallel' ]
Word count: 4

Explanation: split turns a string into an array using a separator.

10. Repeat and padBeginner

Print a divider of 20 dashes and pad test IDs to 4 digits.

Show solution
console.log('-'.repeat(20));
for (const id of [7, 42, 315]) console.log('TC-' + String(id).padStart(4, '0'));

Output

--------------------
TC-0007
TC-0042
TC-0315

Explanation: repeat duplicates a string, and padStart fills it to a fixed length.

JavaScript Intermediate Programs

11. Reverse a stringIntermediate

Reverse 'Playwright'.

Show solution
const reversed = 'Playwright'.split('').reverse().join('');
console.log(reversed);

Output

thgirwyalP

Explanation: strings have no reverse, so split into characters, reverse the array and join it again.

12. Palindrome check ignoring case and spacesIntermediate

Check whether 'Never odd or even' is a palindrome.

Show solution
const text = 'Never odd or even';
const clean = text.toLowerCase().replace(/[^a-z0-9]/g, '');
const isPalindrome = clean === [...clean].reverse().join('');
console.log(clean, isPalindrome);

Output

neveroddoreven true

Explanation: normalise the text first (lower case, letters only), then compare it with its reverse.

13. Count occurrences of a characterIntermediate

Count how many times 't' appears in 'test automation tutorial'.

Show solution
const text = 'test automation tutorial';
let count = 0;
for (const ch of text) if (ch === 't') count++;
console.log(count);
console.log(text.split('t').length - 1);

Output

6
6

Explanation: you can loop over characters, or split on the character and count the pieces minus one.

14. Capitalise each wordIntermediate

Convert 'checkout with saved card' to title case.

Show solution
const title = 'checkout with saved card'
  .split(' ')
  .map(word => word[0].toUpperCase() + word.slice(1))
  .join(' ');
console.log(title);

Output

Checkout With Saved Card

Explanation: split into words, capitalise the first letter of each, and join them back.

15. Character frequency mapIntermediate

Count each character in 'banana'.

Show solution
const freq = {};
for (const ch of 'banana') freq[ch] = (freq[ch] || 0) + 1;
console.log(freq);

Output

{ b: 1, a: 3, n: 2 }

Explanation: an object works as a counter, with each character as a key.

16. Anagram checkIntermediate

Check whether 'listen' and 'silent' are anagrams.

Show solution
const normalise = s => [...s.toLowerCase()].sort().join('');
console.log(normalise('listen') === normalise('silent'));
console.log(normalise('test') === normalise('sets'));

Output

true
false

Explanation: anagrams contain the same letters, so their sorted characters match.

17. camelCase to kebab-caseIntermediate

Convert 'loginButtonText' to 'login-button-text'.

Show solution
const camel = 'loginButtonText';
const kebab = camel.replace(/([A-Z])/g, '-$1').toLowerCase();
console.log(kebab);

Output

login-button-text

Explanation: a regular expression inserts a dash before each capital letter, and lower-casing finishes the job.

18. Longest wordIntermediate

Find the longest word in 'Playwright makes cross browser testing reliable'.

Show solution
const words = 'Playwright makes cross browser testing reliable'.split(' ');
let longest = '';
for (const w of words) if (w.length > longest.length) longest = w;
console.log(longest, longest.length);

Output

Playwright 10

Explanation: track the best word while looping, replacing it only when a longer one appears.

19. Truncate long textIntermediate

Write truncate(text, max) that adds ... when text is longer than max.

Show solution
const truncate = (text, max) => (text.length > max ? text.slice(0, max - 3) + '...' : text);
console.log(truncate('Short title', 20));
console.log(truncate('A very long product name that overflows', 20));

Output

Short title
A very long produ...

Explanation: UI tests often check that long names are cut off, so knowing the exact rule helps.

20. Compare strings ignoring caseIntermediate

Compare 'Submit' and 'SUBMIT' case-insensitively in two ways.

Show solution
const a = 'Submit', b = 'SUBMIT';
console.log(a === b);
console.log(a.toLowerCase() === b.toLowerCase());
console.log(a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0);

Output

false
true
true

Explanation: normalising case, or localeCompare with a sensitivity option, ignores letter case.

JavaScript Real-World QA Scenario Programs

21. Validate an email formatReal-world

Check a list of emails against a simple pattern.

Show solution
const pattern = /^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i;
for (const email of ['qa@example.com', 'qa@example', 'qa example@test.com', 'QA@Shop.IN']) {
  console.log(email.padEnd(20), pattern.test(email) ? 'valid' : 'invalid');
}

Output

qa@example.com       valid
qa@example           invalid
qa example@test.com  invalid
QA@Shop.IN           valid

Explanation: a regular expression describes the allowed format. padEnd aligns the output in columns.

22. Extract the order numberReal-world

Extract ORD-58213 from the confirmation text.

Show solution
const confirmation = 'Thank you! Your order ORD-58213 has been placed.';
const match = confirmation.match(/ORD-\d+/);
console.log(match ? match[0] : 'Not found');

Output

ORD-58213

Explanation: match returns the matched text, so tests can reuse dynamic values shown in the UI.

23. Mask a card numberReal-world

Show only the last 4 digits of '4111 1111 1111 1234'.

Show solution
const card = '4111 1111 1111 1234';
const digits = card.replace(/\s/g, '');
const masked = '**** **** **** ' + digits.slice(-4);
console.log(masked);

Output

**** **** **** 1234

Explanation: remove spaces first so the last four characters are always digits.

24. Build a slug from a titleReal-world

Turn ' Playwright: Getting Started (2026)! ' into 'playwright-getting-started-2026'.

Show solution
const title = '  Playwright: Getting Started (2026)!  ';
const slug = title.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
console.log(slug);

Output

playwright-getting-started-2026

Explanation: replace every run of non-alphanumeric characters with one dash, then trim dashes from the ends.

25. Parse a key=value cookie stringReal-world

Turn 'session=abc123; theme=dark; lang=en' into an object.

Show solution
const cookieText = 'session=abc123; theme=dark; lang=en';
const cookies = {};
for (const part of cookieText.split('; ')) {
  const [key, value] = part.split('=');
  cookies[key] = value;
}
console.log(cookies);

Output

{ session: 'abc123', theme: 'dark', lang: 'en' }

Explanation: split into pairs, then split each pair at =.

26. Normalise whitespace in UI textReal-world

Collapse extra spaces and line breaks in ' Total:\n ₹1,299 '.

Show solution
const uiText = '  Total:\n   ₹1,299  ';
const normalised = uiText.replace(/\s+/g, ' ').trim();
console.log(normalised);

Output

Total: ₹1,299

Explanation: page text often contains line breaks and indentation. Playwright’s toHaveText normalises whitespace the same way.

27. Check the URL path and queryReal-world

Read the path and the q parameter from a search URL.

Show solution
const url = new URL('https://shop.test/search?q=wireless%20mouse&page=2');
console.log(url.pathname);
console.log(url.searchParams.get('q'));
console.log(url.searchParams.get('page'));

Output

/search
wireless mouse
2

Explanation: the URL class parses URLs and decodes values such as %20, which is safer than slicing strings.

28. Template literal reportReal-world

Build a multi-line test report with a template literal.

Show solution
const name = 'Checkout';
const passed = 18, failed = 2;
const report = `Suite: ${name}
Passed: ${passed}
Failed: ${failed}
Status: ${failed === 0 ? 'GREEN' : 'RED'}`;
console.log(report);

Output

Suite: Checkout
Passed: 18
Failed: 2
Status: RED

Explanation: template literals keep line breaks and can include expressions such as ternaries.

29. Compare expected and actual textReal-world

Report the first position where two strings differ.

Show solution
function firstDiff(a, b) {
  const len = Math.max(a.length, b.length);
  for (let i = 0; i < len; i++) if (a[i] !== b[i]) return i;
  return -1;
}
const expected = 'Welcome back, Asha';
const actual = 'Welcome back, Asha!';
const i = firstDiff(expected, actual);
console.log(i === -1 ? 'Texts match' : `Differs at index ${i}: '${expected[i] ?? ''}' vs '${actual[i] ?? ''}'`);

Output

Differs at index 18: '' vs '!'

Explanation: pinpointing the first difference makes text-assertion failures much quicker to debug.

30. Extract all hashtagsReal-world

Find all hashtags in a social post.

Show solution
const post = 'Learning #Playwright with #TypeScript for #QA automation';
const tags = post.match(/#\w+/g) || [];
console.log(tags.join(', '));
console.log(tags.length);

Output

#Playwright, #TypeScript, #QA
3

Explanation: the g flag returns every match. || [] avoids errors when nothing matches.

31. Format a name for displayReal-world

Convert ' ASHA sharma ' into 'Asha Sharma'.

Show solution
const raw = '  ASHA   sharma ';
const display = raw
  .trim()
  .split(/\s+/)
  .map(part => part[0].toUpperCase() + part.slice(1).toLowerCase())
  .join(' ');
console.log(display);

Output

Asha Sharma

Explanation: splitting on \s+ handles any number of spaces between words.

32. Count words in a reviewReal-world

Count the words in a review, ignoring extra spaces, and check a 10-word minimum.

Show solution
const review = '  Great product,   fast delivery and   very good packaging  ';
const wordCount = review.trim().split(/\s+/).length;
console.log('Words:', wordCount);
console.log(wordCount >= 10 ? 'Accepted' : 'Too short');

Output

Words: 8
Too short

Explanation: trimming first avoids empty strings at the ends being counted as words.

Keep Practising

JavaScript Function Practice Programs with Solutions (32 Programs)

Practise JavaScript functions with 32 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.

New to this topic? Read the JavaScript Functions lesson first.

JavaScript Beginner Programs

1. Function that greets a userBeginner

Write a function greet(name) that returns Hello, &lt;name&gt;! and print it for two names.

Show solution
function greet(name) {
  return `Hello, ${name}!`;
}
console.log(greet('Asha'));
console.log(greet('Ravi'));

Output

Hello, Asha!
Hello, Ravi!

Explanation: a function declaration takes parameters and uses return to send a value back to the caller.

2. Add two numbersBeginner

Write add(a, b) and print the sum of 12 and 30.

Show solution
function add(a, b) {
  return a + b;
}
const result = add(12, 30);
console.log('Result:', result);

Output

Result: 42

Explanation: the returned value can be stored in a variable or used directly.

3. Arrow functionBeginner

Rewrite a square function as an arrow function and print the squares of 4 and 9.

Show solution
const square = n => n * n;
console.log(square(4));
console.log(square(9));

Output

16
81

Explanation: arrow functions with one expression return it automatically, without return or braces.

4. Default parametersBeginner

Write openPage(url, timeout = 30000) that prints the URL and timeout, and call it with and without a timeout.

Show solution
function openPage(url, timeout = 30000) {
  console.log(`Opening ${url} (timeout ${timeout} ms)`);
}
openPage('/login');
openPage('/reports', 60000);

Output

Opening /login (timeout 30000 ms)
Opening /reports (timeout 60000 ms)

Explanation: default parameters are used when the argument is missing or undefined.

5. Function without returnBeginner

Show what a function without a return statement gives back.

Show solution
function logStep(step) {
  console.log('Step:', step);
}
const value = logStep('Click login');
console.log('Returned:', value);

Output

Step: Click login
Returned: undefined

Explanation: a function with no return returns undefined.

6. Even checkerBeginner

Write isEven(n) that returns true or false, and test it with 4 and 7.

Show solution
const isEven = n => n % 2 === 0;
console.log(isEven(4));
console.log(isEven(7));

Output

true
false

Explanation: functions that return booleans read naturally in conditions, for example if (isEven(x)).

7. Celsius to FahrenheitBeginner

Convert 0, 37 and 100 °C to Fahrenheit with a function.

Show solution
function toFahrenheit(celsius) {
  return (celsius * 9) / 5 + 32;
}
for (const c of [0, 37, 100]) console.log(`${c}°C = ${toFahrenheit(c)}°F`);

Output

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

Explanation: wrapping a formula in a function makes it reusable and easy to test.

8. Function expressionBeginner

Store an anonymous function in a constant and call it.

Show solution
const multiply = function (a, b) {
  return a * b;
};
console.log(multiply(6, 7));
console.log(typeof multiply);

Output

42
function

Explanation: functions are values in JavaScript, so they can be stored in variables.

9. Rest parametersBeginner

Write sum(...numbers) that adds any number of arguments.

Show solution
function sum(...numbers) {
  let total = 0;
  for (const n of numbers) total += n;
  return total;
}
console.log(sum(1, 2));
console.log(sum(5, 10, 15, 20));

Output

3
50

Explanation: ...numbers collects all arguments into a real array.

10. Return multiple valuesBeginner

Return the min and max of a list as an object and destructure the result.

Show solution
function minMax(values) {
  return { min: Math.min(...values), max: Math.max(...values) };
}
const { min, max } = minMax([42, 7, 19, 88]);
console.log('min:', min, 'max:', max);

Output

min: 7 max: 88

Explanation: return an object or array when a function produces more than one value.

JavaScript Intermediate Programs

11. Hoisting of function declarationsIntermediate

Call a function declaration before it is defined, and compare with a function expression.

Show solution
console.log(double(5));
function double(n) { return n * 2; }
try {
  triple(5);
} catch (error) {
  console.log(error.name);
}
const triple = n => n * 3;

Output

10
ReferenceError

Explanation: function declarations are hoisted with their body. A const function is in the temporal dead zone until its line runs.

12. Callback functionIntermediate

Write runTest(name, callback) that prints the name and calls the callback with a result.

Show solution
function runTest(name, callback) {
  console.log('Running', name);
  callback('passed');
}
runTest('login', result => console.log('Result:', result));

Output

Running login
Result: passed

Explanation: a callback is a function passed to another function to be called later.

13. Higher-order function that returns a functionIntermediate

Write makeMultiplier(factor) that returns a function, and create double and triple.

Show solution
function makeMultiplier(factor) {
  return n => n * factor;
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(10), triple(10));

Output

20 30

Explanation: functions can return functions. The returned function remembers factor through a closure.

14. Closure counterIntermediate

Create a counter function that keeps its own private count.

Show solution
function createCounter() {
  let count = 0;
  return () => ++count;
}
const next = createCounter();
console.log(next(), next(), next());
const other = createCounter();
console.log(other());

Output

1 2 3
1

Explanation: each call to createCounter creates a new count that only its returned function can access.

15. Recursion: factorialIntermediate

Calculate 6! with a recursive function.

Show solution
function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}
console.log(factorial(6));

Output

720

Explanation: a recursive function calls itself with a smaller input until it reaches a base case.

16. Recursion: sum nested arraysIntermediate

Sum all numbers in [1, [2, 3], [4, [5]]] with recursion.

Show solution
function deepSum(items) {
  let total = 0;
  for (const item of items) {
    total += Array.isArray(item) ? deepSum(item) : item;
  }
  return total;
}
console.log(deepSum([1, [2, 3], [4, [5]]]));

Output

15

Explanation: recursion handles data whose nesting depth is not known in advance.

17. Pure vs impure functionsIntermediate

Compare a pure function with one that changes outside state.

Show solution
let calls = 0;
const impureAdd = (a, b) => { calls++; return a + b; };
const pureAdd = (a, b) => a + b;
console.log(pureAdd(2, 3), pureAdd(2, 3));
console.log(impureAdd(2, 3), impureAdd(2, 3), 'calls:', calls);

Output

5 5
5 5 calls: 2

Explanation: a pure function always returns the same output for the same input and changes nothing outside itself, which makes it easy to test.

18. Immediately invoked functionIntermediate

Use an IIFE to compute a value without leaking variables.

Show solution
const config = (() => {
  const env = 'qa';
  const port = 8080;
  return `${env}:${port}`;
})();
console.log(config);
console.log(typeof env);

Output

qa:8080
undefined

Explanation: an IIFE runs immediately and keeps its variables private.

19. Memoize a slow functionIntermediate

Cache results of a function so repeated calls are not recalculated.

Show solution
function memoize(fn) {
  const cache = new Map();
  return n => {
    if (cache.has(n)) return `${cache.get(n)} (cached)`;
    const value = fn(n);
    cache.set(n, value);
    return value;
  };
}
const slowSquare = n => n * n;
const fastSquare = memoize(slowSquare);
console.log(fastSquare(12));
console.log(fastSquare(12));

Output

144
144 (cached)

Explanation: a closure keeps the cache between calls. Memoization trades memory for speed.

20. Arguments with destructured optionsIntermediate

Write createUser({ name, role = 'viewer', active = true }) and call it with partial options.

Show solution
function createUser({ name, role = 'viewer', active = true }) {
  return `${name} | ${role} | ${active ? 'active' : 'inactive'}`;
}
console.log(createUser({ name: 'Asha' }));
console.log(createUser({ name: 'Ravi', role: 'admin', active: false }));

Output

Asha | viewer | active
Ravi | admin | inactive

Explanation: an options object with destructuring and defaults keeps calls readable when a function has many settings.

JavaScript Real-World QA Scenario Programs

21. Reusable assertion helperReal-world

Write assertEqual(actual, expected, message) that prints PASS or FAIL.

Show solution
function assertEqual(actual, expected, message) {
  const ok = actual === expected;
  console.log(`${ok ? 'PASS' : 'FAIL'}: ${message}${ok ? '' : ` (expected ${expected}, got ${actual})`}`);
  return ok;
}
assertEqual(2 + 2, 4, 'adds numbers');
assertEqual('Login'.toLowerCase(), 'login', 'lower-cases text');
assertEqual(10 / 4, 2, 'divides numbers');

Output

PASS: adds numbers
PASS: lower-cases text
FAIL: divides numbers (expected 2, got 2.5)

Explanation: small helpers make checks consistent. Real tests use Playwright’s expect, which works the same way.

22. Build a URL helperReal-world

Write buildUrl(base, path, params) that joins a base URL, a path and query parameters.

Show solution
function buildUrl(base, path, params = {}) {
  const url = new URL(path, base);
  for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
  return url.toString();
}
console.log(buildUrl('https://shop.test', '/search', { q: 'laptop', page: 2 }));
console.log(buildUrl('https://shop.test', '/cart'));

Output

https://shop.test/search?q=laptop&page=2
https://shop.test/cart

Explanation: a helper avoids hand-building URLs, and URL takes care of encoding query values.

23. Generate unique test emailsReal-world

Write uniqueEmail(prefix, id) that returns a unique email address.

Show solution
const uniqueEmail = (prefix, id) => `${prefix}.${id}@example.com`;
for (let i = 1; i <= 3; i++) console.log(uniqueEmail('qa.signup', 1000 + i));

Output

qa.signup.1001@example.com
qa.signup.1002@example.com
qa.signup.1003@example.com

Explanation: a tiny pure function keeps test-data rules in one place.

24. Retry wrapperReal-world

Write retry(fn, attempts) that calls a function until it succeeds or attempts run out.

Show solution
function retry(fn, attempts) {
  for (let i = 1; i <= attempts; i++) {
    try {
      return fn(i);
    } catch (error) {
      console.log(`Attempt ${i} failed: ${error.message}`);
    }
  }
  throw new Error('All attempts failed');
}
const flaky = attempt => {
  if (attempt < 3) throw new Error('element not ready');
  return 'clicked';
};
console.log(retry(flaky, 5));

Output

Attempt 1 failed: element not ready
Attempt 2 failed: element not ready
clicked

Explanation: wrapping retry logic in a function means every flaky step can reuse the same behaviour.

25. Format test durationReal-world

Write formatDuration(ms) that returns values like 850 ms, 2.5 s or 1m 5s.

Show solution
function formatDuration(ms) {
  if (ms < 1000) return `${ms} ms`;
  if (ms < 60000) return `${(ms / 1000).toFixed(1)} s`;
  const minutes = Math.floor(ms / 60000);
  const seconds = Math.round((ms % 60000) / 1000);
  return `${minutes}m ${seconds}s`;
}
for (const ms of [850, 2500, 65000]) console.log(formatDuration(ms));

Output

850 ms
2.5 s
1m 5s

Explanation: one formatting function keeps reports consistent.

26. Validate form inputReal-world

Write validateSignup(data) that returns a list of error messages.

Show solution
function validateSignup({ email = '', password = '', age }) {
  const errors = [];
  if (!email.includes('@')) errors.push('Email is invalid');
  if (password.length < 8) errors.push('Password is too short');
  if (!(age >= 18)) errors.push('Must be 18 or older');
  return errors;
}
const show = errors => console.log(errors.length ? errors.join('; ') : 'No errors');
show(validateSignup({ email: 'qa@test.com', password: 'Secret123', age: 25 }));
show(validateSignup({ email: 'qa', password: '123', age: 16 }));

Output

No errors
Email is invalid; Password is too short; Must be 18 or older

Explanation: returning all errors at once lets a test assert every validation message on the form.

27. Debounce a searchReal-world

Write a debounce function so that only the last of several quick calls runs.

Show solution
function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}
const search = debounce(term => console.log('Searching for:', term), 30);
search('p');
search('pl');
search('play');
await new Promise(resolve => setTimeout(resolve, 60));

Output

Searching for: play

Explanation: debouncing waits until calls stop, which is how search boxes avoid one request per keystroke.

28. Compose small functionsReal-world

Combine trim, lowercase and slugify steps into one pipeline function.

Show solution
const pipe = (...fns) => value => fns.reduce((acc, fn) => fn(acc), value);
const trim = s => s.trim();
const lower = s => s.toLowerCase();
const slugify = s => s.replace(/\s+/g, '-');
const toSlug = pipe(trim, lower, slugify);
console.log(toSlug('  Playwright Mock Test  '));

Output

playwright-mock-test

Explanation: composing small single-purpose functions builds bigger behaviour that is easy to test piece by piece.

29. Price calculator with optionsReal-world

Write calculateTotal(items, { taxRate, coupon }) and test two carts.

Show solution
function calculateTotal(items, { taxRate = 0.18, coupon = 0 } = {}) {
  const subtotal = items.reduce((sum, item) => sum + item.price * item.qty, 0);
  const discounted = Math.max(subtotal - coupon, 0);
  return Math.round(discounted * (1 + taxRate));
}
const cart = [{ price: 500, qty: 2 }, { price: 250, qty: 1 }];
console.log(calculateTotal(cart));
console.log(calculateTotal(cart, { coupon: 250, taxRate: 0.05 }));

Output

1475
1050

Explanation: an options object with defaults keeps the function easy to call for common cases.

30. Callback for each test resultReal-world

Write runSuite(tests, onResult) that runs simple checks and calls onResult for each.

Show solution
function runSuite(tests, onResult) {
  for (const test of tests) {
    const passed = test.check();
    onResult(test.name, passed);
  }
}
const tests = [
  { name: 'title is set', check: () => 'Shop'.length > 0 },
  { name: 'cart is empty', check: () => [1].length === 0 }
];
runSuite(tests, (name, passed) => console.log(`${passed ? '✔' : '✘'} ${name}`));

Output

✔ title is set
✘ cart is empty

Explanation: passing a callback lets the caller decide how results are reported, such as in the console, a file or a dashboard.

31. Run a function only onceReal-world

Write a once function that lets a warning print only the first time.

Show solution
function once(fn) {
  let called = false;
  return (...args) => {
    if (called) return;
    called = true;
    fn(...args);
  };
}
const warnDeprecated = once(() => console.log('Warning: page.$() is discouraged, use locators'));
warnDeprecated();
warnDeprecated();
warnDeprecated();

Output

Warning: page.$() is discouraged, use locators

Explanation: a closure flag prevents the same message from flooding the logs.

32. Page-object style functionReal-world

Write a factory createLoginPage() that returns an object with methods that record actions.

Show solution
function createLoginPage() {
  const actions = [];
  return {
    fill(field, value) { actions.push(`fill ${field}=${field === 'password' ? '***' : value}`); return this; },
    submit() { actions.push('click submit'); return this; },
    history() { return actions.join(' -> '); }
  };
}
const page = createLoginPage().fill('email', 'qa@test.com').fill('password', 'secret').submit();
console.log(page.history());

Output

fill email=qa@test.com -> fill password=*** -> click submit

Explanation: returning this from each method allows chaining. This is the same idea as a page object with readable steps.

Keep Practising

JavaScript Loop Practice Programs with Solutions (32 Programs)

Practise JavaScript loops with 32 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.

New to this topic? Read the JavaScript Loops lesson first.

JavaScript Beginner Programs

1. Print 1 to 5 with a for loopBeginner

Print the numbers 1 to 5 on one line.

Show solution
let line = '';
for (let i = 1; i <= 5; i++) {
  line += i + ' ';
}
console.log(line.trim());

Output

1 2 3 4 5

Explanation: a for loop has a start (let i = 1), a condition (i &lt;= 5) and an update (i++).

2. Countdown with a while loopBeginner

Print a countdown from 5 to 1 followed by 'Go!'.

Show solution
let n = 5;
while (n > 0) {
  console.log(n);
  n--;
}
console.log('Go!');

Output

5
4
3
2
1
Go!

Explanation: while repeats as long as its condition is true. Update the variable inside, or the loop never ends.

3. Sum of 1 to 100Beginner

Add up all numbers from 1 to 100.

Show solution
let sum = 0;
for (let i = 1; i <= 100; i++) {
  sum += i;
}
console.log('Sum:', sum);

Output

Sum: 5050

Explanation: an accumulator variable collects the running total on each iteration.

4. Multiplication tableBeginner

Print the multiplication table of 7 from 1 to 10.

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

Output

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

Explanation: the loop counter supplies the multiplier on each pass.

5. Even numbers up to 20Beginner

Print all even numbers from 2 to 20 by stepping 2 at a time.

Show solution
const evens = [];
for (let i = 2; i <= 20; i += 2) {
  evens.push(i);
}
console.log(evens.join(', '));

Output

2, 4, 6, 8, 10, 12, 14, 16, 18, 20

Explanation: the update step can be any expression, such as i += 2.

6. Loop over an array with for…ofBeginner

Print each browser name from an array.

Show solution
const browsers = ['chromium', 'firefox', 'webkit'];
for (const browser of browsers) {
  console.log('Running on', browser);
}

Output

Running on chromium
Running on firefox
Running on webkit

Explanation: for...of gives each value directly, which is the cleanest way to read an array.

7. Index and value with entries()Beginner

Print each test name with its position, starting at 1.

Show solution
const tests = ['login', 'search', 'checkout'];
for (const [index, name] of tests.entries()) {
  console.log(`${index + 1}. ${name}`);
}

Output

1. login
2. search
3. checkout

Explanation: entries() yields [index, value] pairs that you can destructure.

8. Loop over object keys with for…inBeginner

Print every key and value of a config object.

Show solution
const config = { browser: 'chromium', retries: 2, headless: true };
for (const key in config) {
  console.log(`${key} = ${config[key]}`);
}

Output

browser = chromium
retries = 2
headless = true

Explanation: for...in iterates over an object’s keys. Use bracket notation to read each value.

9. Characters of a stringBeginner

Print each character of 'QA' and count the letters in 'Playwright'.

Show solution
for (const ch of 'QA') console.log(ch);
let count = 0;
for (const ch of 'Playwright') count++;
console.log('Letters:', count);

Output

Q
A
Letters: 10

Explanation: strings are iterable, so for...of visits each character.

10. do…while runs at least onceBeginner

Show that do...while runs its body once even when the condition is false.

Show solution
let attempts = 10;
do {
  console.log('Attempt', attempts);
  attempts++;
} while (attempts < 3);
console.log('Finished');

Output

Attempt 10
Finished

Explanation: do...while checks the condition after the body, so the body always runs at least once.

JavaScript Intermediate Programs

11. FactorialIntermediate

Calculate 5! and 10! with a loop.

Show solution
function factorial(n) {
  let result = 1;
  for (let i = 2; i <= n; i++) result *= i;
  return result;
}
console.log(factorial(5));
console.log(factorial(10));

Output

120
3628800

Explanation: multiply an accumulator by each number from 2 to n.

12. Fibonacci seriesIntermediate

Print the first 10 Fibonacci numbers.

Show solution
const fib = [0, 1];
for (let i = 2; i < 10; i++) {
  fib.push(fib[i - 1] + fib[i - 2]);
}
console.log(fib.join(' '));

Output

0 1 1 2 3 5 8 13 21 34

Explanation: each new term is the sum of the previous two.

13. Reverse a numberIntermediate

Reverse the digits of 12345 using a while loop and %.

Show solution
let num = 12345;
let reversed = 0;
while (num > 0) {
  reversed = reversed * 10 + (num % 10);
  num = Math.floor(num / 10);
}
console.log(reversed);

Output

54321

Explanation: % 10 takes the last digit and Math.floor(num / 10) removes it.

14. Prime check with breakIntermediate

Check whether 29 and 33 are prime, stopping as soon as a divisor is found.

Show solution
for (const n of [29, 33]) {
  let isPrime = n > 1;
  for (let d = 2; d * d <= n; d++) {
    if (n % d === 0) {
      isPrime = false;
      break;
    }
  }
  console.log(n, isPrime ? 'is prime' : 'is not prime');
}

Output

29 is prime
33 is not prime

Explanation: break exits the loop early. Checking divisors up to √n is enough.

15. Skip values with continueIntermediate

Print numbers 1 to 10, skipping multiples of 3.

Show solution
const result = [];
for (let i = 1; i <= 10; i++) {
  if (i % 3 === 0) continue;
  result.push(i);
}
console.log(result.join(' '));

Output

1 2 4 5 7 8 10

Explanation: continue skips the rest of the current iteration and moves to the next one.

16. Nested loops: star patternIntermediate

Print a right-angled triangle of stars with 4 rows.

Show solution
for (let row = 1; row <= 4; row++) {
  let line = '';
  for (let col = 1; col <= row; col++) line += '*';
  console.log(line);
}

Output

*
**
***
****

Explanation: the inner loop runs once per row and its length depends on the outer counter.

17. Count vowelsIntermediate

Count the vowels in 'Automation Testing'.

Show solution
const text = 'Automation Testing';
let vowels = 0;
for (const ch of text.toLowerCase()) {
  if ('aeiou'.includes(ch)) vowels++;
}
console.log('Vowels:', vowels);

Output

Vowels: 8

Explanation: loop over each character and count the ones that match a condition.

18. Find the maximum without Math.maxIntermediate

Find the largest value in [34, 78, 12, 99, 45] with a loop.

Show solution
const values = [34, 78, 12, 99, 45];
let max = values[0];
for (const v of values) {
  if (v > max) max = v;
}
console.log('Max:', max);

Output

Max: 99

Explanation: keep the best value seen so far and replace it whenever a larger one appears.

19. Labeled break out of nested loopsIntermediate

Search a grid for the value 7 and stop both loops when it is found.

Show solution
const grid = [[1, 2, 3], [4, 7, 6], [7, 8, 9]];
outer: for (let r = 0; r < grid.length; r++) {
  for (let c = 0; c < grid[r].length; c++) {
    if (grid[r][c] === 7) {
      console.log(`Found 7 at row ${r}, col ${c}`);
      break outer;
    }
  }
}

Output

Found 7 at row 1, col 1

Explanation: a label lets break exit the outer loop, not just the inner one.

20. Palindrome checkIntermediate

Check whether 'level' and 'test' are palindromes using two pointers.

Show solution
for (const word of ['level', 'test']) {
  let isPalindrome = true;
  for (let i = 0, j = word.length - 1; i < j; i++, j--) {
    if (word[i] !== word[j]) {
      isPalindrome = false;
      break;
    }
  }
  console.log(word, isPalindrome);
}

Output

level true
test false

Explanation: compare characters from both ends moving inwards. A for loop can update two variables at once.

JavaScript Real-World QA Scenario Programs

21. Run tests in every browserReal-world

Simulate running three tests in three browsers and print each combination.

Show solution
const browsers = ['chromium', 'firefox', 'webkit'];
const tests = ['login', 'search', 'checkout'];
let runs = 0;
for (const browser of browsers) {
  for (const test of tests) {
    runs++;
  }
}
console.log(`${tests.length} tests x ${browsers.length} browsers = ${runs} runs`);

Output

3 tests x 3 browsers = 9 runs

Explanation: nested loops visit every combination, just like Playwright projects multiply test runs.

22. Retry until successReal-world

Retry a flaky action up to 3 times, where it succeeds on the 3rd attempt.

Show solution
const MAX = 3;
let attempt = 0;
let success = false;
while (attempt < MAX && !success) {
  attempt++;
  success = attempt === 3;
  console.log(`Attempt ${attempt}: ${success ? 'passed' : 'failed'}`);
}
console.log(success ? 'Action succeeded' : 'Gave up');

Output

Attempt 1: failed
Attempt 2: failed
Attempt 3: passed
Action succeeded

Explanation: the loop stops when it succeeds or runs out of attempts, whichever comes first.

23. Poll for a status changeReal-world

Poll a job status list until it reports 'done', with a maximum of 5 polls.

Show solution
const statuses = ['queued', 'running', 'running', 'done', 'done'];
let polls = 0;
let status;
do {
  status = statuses[polls];
  polls++;
  console.log(`Poll ${polls}: ${status}`);
} while (status !== 'done' && polls < 5);

Output

Poll 1: queued
Poll 2: running
Poll 3: running
Poll 4: done

Explanation: polling loops need both a success condition and a limit, so tests never hang forever.

24. Summarise test resultsReal-world

Count passed, failed and skipped results in one loop.

Show solution
const results = ['passed', 'failed', 'passed', 'skipped', 'passed', 'failed'];
const summary = { passed: 0, failed: 0, skipped: 0 };
for (const r of results) summary[r]++;
console.log(summary);

Output

{ passed: 3, failed: 2, skipped: 1 }

Explanation: use each status as a key in a counter object and increment it inside the loop.

25. Find the first failed testReal-world

Stop at the first failed test and print its name and position.

Show solution
const runs = [
  { name: 'login', status: 'passed' },
  { name: 'search', status: 'failed' },
  { name: 'checkout', status: 'failed' }
];
for (let i = 0; i < runs.length; i++) {
  if (runs[i].status === 'failed') {
    console.log(`First failure: ${runs[i].name} (#${i + 1})`);
    break;
  }
}

Output

First failure: search (#2)

Explanation: break stops as soon as the first match is found, so later items are not checked.

26. Total a shopping cartReal-world

Loop over cart items and calculate the total price.

Show solution
const cart = [
  { item: 'Keyboard', price: 1499, qty: 1 },
  { item: 'Mouse', price: 599, qty: 2 },
  { item: 'Cable', price: 199, qty: 3 }
];
let total = 0;
for (const { price, qty } of cart) total += price * qty;
console.log('Cart total:', total);

Output

Cart total: 3294

Explanation: destructuring in the for...of header reads just the fields the calculation needs.

27. Generate test usersReal-world

Generate 3 test users with numbered usernames and emails.

Show solution
const users = [];
for (let i = 1; i <= 3; i++) {
  users.push({ username: `qa_user${i}`, email: `qa_user${i}@example.com` });
}
for (const u of users) console.log(u.username, u.email);

Output

qa_user1 qa_user1@example.com
qa_user2 qa_user2@example.com
qa_user3 qa_user3@example.com

Explanation: a counter loop is a simple way to build numbered test data.

28. Validate every emailReal-world

Check each email in a list and print the invalid ones.

Show solution
const emails = ['a@test.com', 'bad-email', 'qa@shop.in', 'no@domain'];
const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
for (const email of emails) {
  if (!pattern.test(email)) console.log('Invalid:', email);
}
console.log('Checked', emails.length, 'emails');

Output

Invalid: bad-email
Invalid: no@domain
Checked 4 emails

Explanation: a loop applies the same validation to every item and reports only the failures.

29. Paginate through resultsReal-world

Read pages of results until a page is empty, counting the total items.

Show solution
const pages = [[1, 2, 3], [4, 5, 6], [7], []];
let page = 0;
let total = 0;
while (pages[page].length > 0) {
  total += pages[page].length;
  page++;
}
console.log(`Read ${page} pages, ${total} items`);

Output

Read 3 pages, 7 items

Explanation: pagination loops continue until the server returns an empty page.

30. Compare two listsReal-world

Find expected menu items missing from the actual menu.

Show solution
const expected = ['Home', 'Products', 'About', 'Contact'];
const actual = ['Home', 'About', 'Blog'];
const missing = [];
for (const item of expected) {
  if (!actual.includes(item)) missing.push(item);
}
console.log('Missing:', missing.join(', '));

Output

Missing: Products, Contact

Explanation: loop over one list and check membership in the other to find differences.

31. Table rows to objectsReal-world

Convert table rows (arrays) into objects using a header row.

Show solution
const header = ['id', 'name', 'status'];
const rows = [['1', 'login', 'pass'], ['2', 'search', 'fail']];
for (const row of rows) {
  const record = {};
  for (let i = 0; i < header.length; i++) record[header[i]] = row[i];
  console.log(record);
}

Output

{ id: '1', name: 'login', status: 'pass' }
{ id: '2', name: 'search', status: 'fail' }

Explanation: the inner loop pairs each header with the value at the same position, which is how web tables are usually read.

32. Wait with async delays in a loopReal-world

Simulate three steps that each wait 20 ms, running one after another with for...of and await.

Show solution
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const steps = ['open page', 'fill form', 'submit'];
for (const step of steps) {
  await sleep(20);
  console.log('Done:', step);
}
console.log('All steps finished in order');

Output

Done: open page
Done: fill form
Done: submit
All steps finished in order

Explanation: for...of with await runs async steps sequentially, which is how Playwright actions run. forEach would not wait. (Top-level await works in ES modules, such as .mjs files or "type": "module".)

Keep Practising

JavaScript If-Else Practice Programs with Solutions (31 Programs)

Practise JavaScript if-else conditions with 31 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.

New to this topic? Read the JavaScript If Conditions lesson first.

JavaScript Beginner Programs

1. Positive, negative or zeroBeginner

Print whether each of 5, -3 and 0 is positive, negative or zero.

Show solution
for (const n of [5, -3, 0]) {
  if (n > 0) {
    console.log(n, 'is positive');
  } else if (n < 0) {
    console.log(n, 'is negative');
  } else {
    console.log(n, 'is zero');
  }
}

Output

5 is positive
-3 is negative
0 is zero

Explanation: an if / else if / else chain checks conditions in order and runs only the first matching branch.

2. Voting eligibilityBeginner

Print 'Eligible' when age is 18 or more, otherwise 'Not eligible', for ages 17 and 21.

Show solution
for (const age of [17, 21]) {
  if (age >= 18) {
    console.log(age, 'Eligible');
  } else {
    console.log(age, 'Not eligible');
  }
}

Output

17 Not eligible
21 Eligible

Explanation: if/else chooses between two outcomes based on one condition.

3. Largest of two numbersBeginner

Print the larger of 42 and 57.

Show solution
const a = 42;
const b = 57;
if (a > b) {
  console.log('Larger:', a);
} else {
  console.log('Larger:', b);
}

Output

Larger: 57

Explanation: a single comparison decides which branch runs.

4. Largest of three numbersBeginner

Find the largest of 12, 45 and 30 using if statements.

Show solution
const a = 12, b = 45, c = 30;
let largest;
if (a >= b && a >= c) {
  largest = a;
} else if (b >= a && b >= c) {
  largest = b;
} else {
  largest = c;
}
console.log('Largest:', largest);

Output

Largest: 45

Explanation: combine comparisons with &amp;&amp; so each branch checks one number against both others.

5. Leap yearBeginner

Check whether 2024, 1900 and 2000 are leap years.

Show solution
for (const year of [2024, 1900, 2000]) {
  const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  if (leap) console.log(year, 'is a leap year');
  else console.log(year, 'is not a leap year');
}

Output

2024 is a leap year
1900 is not a leap year
2000 is a leap year

Explanation: a year divisible by 4 is a leap year unless it is divisible by 100, but years divisible by 400 are leap years again.

6. Grade from marksBeginner

Convert marks 92, 78, 65 and 40 into grades A (90+), B (75+), C (60+) or F.

Show solution
for (const marks of [92, 78, 65, 40]) {
  let grade;
  if (marks >= 90) grade = 'A';
  else if (marks >= 75) grade = 'B';
  else if (marks >= 60) grade = 'C';
  else grade = 'F';
  console.log(marks, grade);
}

Output

92 A
78 B
65 C
40 F

Explanation: check the highest threshold first, so each value lands in the correct band.

7. Vowel or consonantBeginner

Check whether the letters 'e', 'K' and 'u' are vowels.

Show solution
for (const letter of ['e', 'K', 'u']) {
  if ('aeiou'.includes(letter.toLowerCase())) {
    console.log(letter, 'is a vowel');
  } else {
    console.log(letter, 'is a consonant');
  }
}

Output

e is a vowel
K is a consonant
u is a vowel

Explanation: includes checks membership, and toLowerCase makes the check case-insensitive.

8. Day name with switchBeginner

Print the day name for day numbers 1, 6 and 9 using switch.

Show solution
for (const day of [1, 6, 9]) {
  switch (day) {
    case 1: console.log(day, 'Monday'); break;
    case 2: console.log(day, 'Tuesday'); break;
    case 3: console.log(day, 'Wednesday'); break;
    case 4: console.log(day, 'Thursday'); break;
    case 5: console.log(day, 'Friday'); break;
    case 6: console.log(day, 'Saturday'); break;
    case 7: console.log(day, 'Sunday'); break;
    default: console.log(day, 'Invalid day');
  }
}

Output

1 Monday
6 Saturday
9 Invalid day

Explanation: switch compares one value against many cases. break stops execution falling into the next case.

9. Weekday or weekend with grouped casesBeginner

Use grouped case labels to print whether a day name is a weekday or the weekend.

Show solution
for (const day of ['Saturday', 'Tuesday']) {
  switch (day) {
    case 'Saturday':
    case 'Sunday':
      console.log(day, 'is the weekend');
      break;
    default:
      console.log(day, 'is a weekday');
  }
}

Output

Saturday is the weekend
Tuesday is a weekday

Explanation: stacked case labels without break share one block of code.

10. Check divisibilityBeginner

Check whether 30 is divisible by 3 and 5, and print FizzBuzz-style output.

Show solution
const n = 30;
if (n % 3 === 0 && n % 5 === 0) console.log('FizzBuzz');
else if (n % 3 === 0) console.log('Fizz');
else if (n % 5 === 0) console.log('Buzz');
else console.log(n);

Output

FizzBuzz

Explanation: check the most specific condition (both divisors) first, otherwise an earlier branch would catch it.

JavaScript Intermediate Programs

11. Nested conditionsIntermediate

Grant access when the user is logged in, then check the role inside.

Show solution
const users = [
  { name: 'Asha', loggedIn: true, role: 'admin' },
  { name: 'Ravi', loggedIn: true, role: 'viewer' },
  { name: 'Guest', loggedIn: false, role: 'viewer' }
];
for (const u of users) {
  if (u.loggedIn) {
    if (u.role === 'admin') console.log(u.name, '-> full access');
    else console.log(u.name, '-> read-only access');
  } else {
    console.log(u.name, '-> please log in');
  }
}

Output

Asha -> full access
Ravi -> read-only access
Guest -> please log in

Explanation: a nested if makes a second decision only after the first condition is true.

12. Guard clausesIntermediate

Rewrite nested checks as early returns in a validateAge function.

Show solution
function validateAge(age) {
  if (typeof age !== 'number') return 'Age must be a number';
  if (age < 0) return 'Age cannot be negative';
  if (age > 120) return 'Age looks unrealistic';
  return 'Age is valid';
}
console.log(validateAge('20'));
console.log(validateAge(-1));
console.log(validateAge(35));

Output

Age must be a number
Age cannot be negative
Age is valid

Explanation: guard clauses exit early on invalid input, keeping the main logic flat and readable.

13. Truthy checks in conditionsIntermediate

Print whether each value would enter an if block.

Show solution
const values = [0, 'qa', '', [], null];
const labels = ['0', "'qa'", "''", '[]', 'null'];
values.forEach((value, i) => {
  if (value) console.log(labels[i], '-> runs');
  else console.log(labels[i], '-> skipped');
});

Output

0 -> skipped
'qa' -> runs
'' -> skipped
[] -> runs
null -> skipped

Explanation: if checks truthiness, not just true. Empty arrays are truthy, while 0, '' and null are falsy.

14. switch with true for rangesIntermediate

Use switch (true) to classify response times of 120, 600 and 2500 ms.

Show solution
for (const ms of [120, 600, 2500]) {
  switch (true) {
    case ms < 200: console.log(ms, 'fast'); break;
    case ms < 1000: console.log(ms, 'acceptable'); break;
    default: console.log(ms, 'slow');
  }
}

Output

120 fast
600 acceptable
2500 slow

Explanation: switch (true) runs the first case whose expression is true, which works for ranges.

15. Object lookup instead of switchIntermediate

Map HTTP status codes to messages with an object lookup and a default.

Show solution
const messages = { 200: 'OK', 201: 'Created', 404: 'Not Found', 500: 'Server Error' };
for (const code of [200, 404, 418]) {
  console.log(code, messages[code] ?? 'Unknown status');
}

Output

200 OK
404 Not Found
418 Unknown status

Explanation: a lookup object replaces long switch statements when each case only returns a value.

16. Ternary for short decisionsIntermediate

Print '1 test' or 'N tests' using a ternary for the plural.

Show solution
for (const count of [1, 5, 0]) {
  console.log(`${count} ${count === 1 ? 'test' : 'tests'}`);
}

Output

1 test
5 tests
0 tests

Explanation: a ternary is ideal for small inline decisions such as singular and plural words.

17. Check string patternsIntermediate

Classify inputs as an email, a phone number or unknown.

Show solution
const inputs = ['qa@example.com', '9876543210', 'hello'];
for (const input of inputs) {
  if (input.includes('@') && input.includes('.')) console.log(input, '-> email');
  else if (/^\d{10}$/.test(input)) console.log(input, '-> phone');
  else console.log(input, '-> unknown');
}

Output

qa@example.com -> email
9876543210 -> phone
hello -> unknown

Explanation: conditions can combine string methods and regular expressions to classify text.

18. Triangle typeIntermediate

Classify triangles with sides (3,3,3), (3,4,4) and (3,4,5).

Show solution
const triangles = [[3, 3, 3], [3, 4, 4], [3, 4, 5]];
for (const [a, b, c] of triangles) {
  let type;
  if (a === b && b === c) type = 'equilateral';
  else if (a === b || b === c || a === c) type = 'isosceles';
  else type = 'scalene';
  console.log(`${a},${b},${c} -> ${type}`);
}

Output

3,3,3 -> equilateral
3,4,4 -> isosceles
3,4,5 -> scalene

Explanation: check the strictest case (all equal) before the looser one (any two equal).

19. Electricity bill slabsIntermediate

Calculate a bill where the first 100 units cost 5, the next 100 cost 7 and the rest cost 10 each, for 250 units.

Show solution
const units = 250;
let bill;
if (units <= 100) {
  bill = units * 5;
} else if (units <= 200) {
  bill = 100 * 5 + (units - 100) * 7;
} else {
  bill = 100 * 5 + 100 * 7 + (units - 200) * 10;
}
console.log('Bill:', bill);

Output

Bill: 1700

Explanation: each branch adds up the full slabs below it plus the partial slab the value falls in.

20. Optional values with ?? in conditionsIntermediate

Print a configured or default browser name, treating an empty string as a valid configured value.

Show solution
for (const configured of ['firefox', '', undefined]) {
  const browser = configured ?? 'chromium';
  console.log(JSON.stringify(configured) ?? 'undefined', '->', JSON.stringify(browser));
}

Output

"firefox" -> "firefox"
"" -> ""
undefined -> "chromium"

Explanation: ?? only falls back for null and undefined. Use || when empty strings should also fall back.

JavaScript Real-World QA Scenario Programs

21. Map a test status to an exit codeReal-world

Return exit code 0 for passed or skipped, 1 for failed and 2 for anything else.

Show solution
function exitCode(status) {
  switch (status) {
    case 'passed':
    case 'skipped':
      return 0;
    case 'failed':
      return 1;
    default:
      return 2;
  }
}
for (const s of ['passed', 'failed', 'skipped', 'timedOut']) console.log(s, exitCode(s));

Output

passed 0
failed 1
skipped 0
timedOut 2

Explanation: CI systems read exit codes, and switch maps each status to its code clearly.

22. Validate a passwordReal-world

Check a password for length (8+), a digit and an uppercase letter, and print the first failing rule.

Show solution
function checkPassword(pw) {
  if (pw.length < 8) return 'Too short';
  if (!/\d/.test(pw)) return 'Needs a digit';
  if (!/[A-Z]/.test(pw)) return 'Needs an uppercase letter';
  return 'Strong';
}
for (const pw of ['abc', 'abcdefgh', 'abcdefg1', 'Abcdefg1']) console.log(pw, '->', checkPassword(pw));

Output

abc -> Too short
abcdefgh -> Needs a digit
abcdefg1 -> Needs an uppercase letter
Abcdefg1 -> Strong

Explanation: guard clauses report the first rule that fails, which mirrors how form validation messages appear.

23. Choose environment URLReal-world

Select a base URL from an ENV value, defaulting to QA for unknown values.

Show solution
function baseUrlFor(env) {
  if (env === 'prod') return 'https://shop.test';
  if (env === 'staging') return 'https://staging.shop.test';
  return 'https://qa.shop.test';
}
for (const env of ['prod', 'staging', 'dev']) console.log(env, '->', baseUrlFor(env));

Output

prod -> https://shop.test
staging -> https://staging.shop.test
dev -> https://qa.shop.test

Explanation: conditions centralise environment selection, with a safe default for anything unexpected.

24. Shipping cost rulesReal-world

Free shipping over 999, 49 for 500–999 and 99 below 500. Calculate it for three cart totals.

Show solution
for (const total of [1200, 750, 300]) {
  let shipping;
  if (total > 999) shipping = 0;
  else if (total >= 500) shipping = 49;
  else shipping = 99;
  console.log(`Cart ${total} -> shipping ${shipping}`);
}

Output

Cart 1200 -> shipping 0
Cart 750 -> shipping 49
Cart 300 -> shipping 99

Explanation: boundary values (999, 500) are where bugs hide, so test values on and around each threshold.

25. Boundary value checksReal-world

For the shipping rule above, generate the boundary inputs 499, 500, 999 and 1000 and print the result for each.

Show solution
const shippingFor = total => (total > 999 ? 0 : total >= 500 ? 49 : 99);
for (const total of [499, 500, 999, 1000]) {
  console.log(total, shippingFor(total));
}

Output

499 99
500 49
999 49
1000 0

Explanation: boundary value analysis checks each edge, because off-by-one mistakes like &gt; versus &gt;= are common.

26. Decide test priorityReal-world

Mark a test as P1 if it is on the checkout path or a blocker, P2 if it is a regression test, otherwise P3.

Show solution
const tests = [
  { id: 'TC1', area: 'checkout', blocker: false, regression: true },
  { id: 'TC2', area: 'profile', blocker: true, regression: false },
  { id: 'TC3', area: 'search', blocker: false, regression: true },
  { id: 'TC4', area: 'help', blocker: false, regression: false }
];
for (const t of tests) {
  let priority;
  if (t.area === 'checkout' || t.blocker) priority = 'P1';
  else if (t.regression) priority = 'P2';
  else priority = 'P3';
  console.log(t.id, priority);
}

Output

TC1 P1
TC2 P1
TC3 P2
TC4 P3

Explanation: ordered conditions turn a written triage rule into code that is easy to review.

27. Verify a sort orderReal-world

Check whether a list of prices from the UI is sorted ascending and print a message.

Show solution
const prices = [99, 149, 149, 299, 250];
let sorted = true;
for (let i = 1; i < prices.length; i++) {
  if (prices[i] < prices[i - 1]) {
    console.log(`Out of order at index ${i}: ${prices[i - 1]} > ${prices[i]}`);
    sorted = false;
    break;
  }
}
if (sorted) console.log('Prices are sorted');

Output

Out of order at index 4: 299 > 250

Explanation: compare each item with the previous one. The if reports exactly where the order breaks.

28. Check an API responseReal-world

Report a clear message for different status and body combinations.

Show solution
const responses = [
  { status: 200, body: { items: [1, 2] } },
  { status: 200, body: { items: [] } },
  { status: 401, body: null },
  { status: 503, body: null }
];
for (const res of responses) {
  if (res.status >= 500) console.log(res.status, 'Server error - retry later');
  else if (res.status === 401) console.log(res.status, 'Unauthorized - check token');
  else if (res.body.items.length === 0) console.log(res.status, 'OK but no items');
  else console.log(res.status, `OK with ${res.body.items.length} items`);
}

Output

200 OK with 2 items
200 OK but no items
401 Unauthorized - check token
503 Server error - retry later

Explanation: check error statuses before reading the body, so you never access items on a null body.

29. Feature availability by planReal-world

Show which features a user can use based on their plan.

Show solution
function canUse(plan, feature) {
  if (feature === 'reports') return plan === 'pro' || plan === 'enterprise';
  if (feature === 'sso') return plan === 'enterprise';
  return true;
}
for (const plan of ['free', 'pro', 'enterprise']) {
  console.log(plan, 'reports:', canUse(plan, 'reports'), 'sso:', canUse(plan, 'sso'));
}

Output

free reports: false sso: false
pro reports: true sso: false
enterprise reports: true sso: true

Explanation: one function with clear conditions is easy to cover with a test per plan and feature.

30. Classify a flaky testReal-world

Classify a test as stable, flaky or broken from its pass count over 10 runs.

Show solution
for (const passes of [10, 7, 0]) {
  const runs = 10;
  let label;
  if (passes === runs) label = 'stable';
  else if (passes === 0) label = 'broken';
  else label = 'flaky';
  console.log(`${passes}/${runs} passed -> ${label}`);
}

Output

10/10 passed -> stable
7/10 passed -> flaky
0/10 passed -> broken

Explanation: a test that sometimes passes and sometimes fails is flaky. Always passing or always failing is deterministic.

31. Business days onlyReal-world

Skip weekend dates when scheduling a test run, using getUTCDay().

Show solution
const dates = ['2026-11-06', '2026-11-07', '2026-11-08', '2026-11-09'];
for (const d of dates) {
  const day = new Date(d + 'T00:00:00Z').getUTCDay();
  if (day === 0 || day === 6) console.log(d, 'weekend - skip');
  else console.log(d, 'run tests');
}

Output

2026-11-06 run tests
2026-11-07 weekend - skip
2026-11-08 weekend - skip
2026-11-09 run tests

Explanation: getUTCDay() returns 0 for Sunday and 6 for Saturday. Using UTC avoids time-zone surprises.

Keep Practising

JavaScript Operators Practice Programs with Solutions (32 Programs)

Practise JavaScript operators with 32 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.

New to this topic? Read the JavaScript Operators lesson first.

JavaScript Beginner Programs

1. Basic arithmeticBeginner

Given a = 17 and b = 5, print their sum, difference, product, quotient and remainder.

Show solution
const a = 17;
const b = 5;
console.log('Sum:', a + b);
console.log('Difference:', a - b);
console.log('Product:', a * b);
console.log('Quotient:', a / b);
console.log('Remainder:', a % b);

Output

Sum: 22
Difference: 12
Product: 85
Quotient: 3.4
Remainder: 2

Explanation: % returns the remainder after division. / always gives a decimal result when the division is not exact.

2. Exponent operatorBeginner

Print 2 to the power of 10 using ** and Math.pow.

Show solution
console.log(2 ** 10);
console.log(Math.pow(2, 10));

Output

1024
1024

Explanation: ** is the exponent operator and gives the same result as Math.pow.

3. Even or odd with modulusBeginner

Use % to print whether 7 and 12 are even or odd.

Show solution
for (const n of [7, 12]) {
  console.log(n, n % 2 === 0 ? 'is even' : 'is odd');
}

Output

7 is odd
12 is even

Explanation: a number is even when dividing by 2 leaves no remainder.

4. Compound assignmentBeginner

Start with total = 100 and apply +=, -=, *=, /= and %= one after another, printing each result.

Show solution
let total = 100;
total += 20; console.log(total);
total -= 10; console.log(total);
total *= 2; console.log(total);
total /= 4; console.log(total);
total %= 50; console.log(total);

Output

120
110
220
55
5

Explanation: compound operators update a variable using its current value, so total += 20 means total = total + 20.

5. Comparison operatorsBeginner

Compare score = 75 with 70 using &gt;, &lt;, &gt;=, &lt;=, === and !==.

Show solution
const score = 75;
console.log(score > 70, score < 70);
console.log(score >= 75, score <= 74);
console.log(score === 75, score !== 75);

Output

true false
true false
true false

Explanation: comparison operators return booleans that you can use in conditions and assertions.

6. Strict vs loose equalityBeginner

Compare '5' and 5 with == and ===.

Show solution
console.log('5' == 5);
console.log('5' === 5);
console.log('5' != 5);
console.log('5' !== 5);

Output

true
false
false
true

Explanation: == converts types before comparing, while === also checks the type. Prefer === in test code.

7. Logical AND, OR, NOTBeginner

With isLoggedIn = true and isAdmin = false, print the results of &amp;&amp;, || and !.

Show solution
const isLoggedIn = true;
const isAdmin = false;
console.log(isLoggedIn && isAdmin);
console.log(isLoggedIn || isAdmin);
console.log(!isAdmin);

Output

false
true
true

Explanation: &amp;&amp; needs both sides true, || needs at least one, and ! flips a boolean.

8. Increment and decrementBeginner

Show the difference between x++ and ++x.

Show solution
let x = 5;
console.log(x++);
console.log(x);
let y = 5;
console.log(++y);
console.log(y);

Output

5
6
6
6

Explanation: postfix x++ returns the old value and then increments. Prefix ++y increments first and returns the new value.

9. String concatenation with +Beginner

Join a first name and last name with a space using +, then add a number to a string.

Show solution
const firstName = 'Neha';
const lastName = 'Verma';
console.log(firstName + ' ' + lastName);
console.log('Build #' + 42);

Output

Neha Verma
Build #42

Explanation: when either side of + is a string, the other side is converted and the values are joined.

10. Ternary operatorBeginner

Use the ternary operator to print 'PASS' when score &gt;= 60 and 'FAIL' otherwise, for 72 and 45.

Show solution
for (const score of [72, 45]) {
  const result = score >= 60 ? 'PASS' : 'FAIL';
  console.log(score, result);
}

Output

72 PASS
45 FAIL

Explanation: condition ? a : b returns a when the condition is truthy, otherwise b.

JavaScript Intermediate Programs

11. Short-circuit with &&Intermediate

Call a function only when a flag is true, using &amp;&amp;.

Show solution
function takeScreenshot() {
  console.log('Screenshot taken');
  return true;
}
const debug = true;
const ci = false;
debug && takeScreenshot();
ci && takeScreenshot();
console.log('Done');

Output

Screenshot taken
Done

Explanation: &amp;&amp; stops at the first falsy value, so the function on its right runs only when the left side is truthy.

12. || vs ?? for defaultsIntermediate

Use both || and ?? to default a timeout of 0, null and undefined to 5000.

Show solution
for (const value of [0, null, undefined]) {
  console.log(String(value), '| ||:', value || 5000, '| ??:', value ?? 5000);
}

Output

0 | ||: 5000 | ??: 0
null | ||: 5000 | ??: 5000
undefined | ||: 5000 | ??: 5000

Explanation: || replaces every falsy value, including a valid 0. ?? only replaces null and undefined.

13. Logical assignment operatorsIntermediate

Use ||=, &amp;&amp;= and ??= on a settings object.

Show solution
const settings = { name: '', retries: null, headless: true };
settings.name ||= 'default-suite';
settings.retries ??= 2;
settings.headless &&= false;
console.log(settings);

Output

{ name: 'default-suite', retries: 2, headless: false }

Explanation: a ||= b assigns only if a is falsy, a ??= b only if a is null or undefined, and a &amp;&amp;= b only if a is truthy.

14. Optional chainingIntermediate

Safely read user.address.city when address may be missing.

Show solution
const withAddress = { name: 'Asha', address: { city: 'Delhi' } };
const withoutAddress = { name: 'Ravi' };
console.log(withAddress.address?.city);
console.log(withoutAddress.address?.city);
console.log(withoutAddress.address?.city ?? 'N/A');

Output

Delhi
undefined
N/A

Explanation: ?. returns undefined instead of throwing when the left side is null or undefined.

15. Operator precedenceIntermediate

Predict and print the results of 2 + 3 * 4, (2 + 3) * 4 and 10 - 4 - 3.

Show solution
console.log(2 + 3 * 4);
console.log((2 + 3) * 4);
console.log(10 - 4 - 3);
console.log(2 ** 3 ** 2);

Output

14
20
3
512

Explanation: * binds tighter than +, subtraction runs left to right, and ** runs right to left (3 ** 2 first).

16. typeof and instanceofIntermediate

Use typeof on a primitive and instanceof on an object.

Show solution
const today = new Date(0);
const tags = ['smoke'];
console.log(typeof 'text');
console.log(today instanceof Date);
console.log(tags instanceof Array);
console.log(tags instanceof Object);

Output

string
true
true
true

Explanation: typeof names primitive types, while instanceof checks whether an object was created by a constructor.

17. The in operatorIntermediate

Check whether a config object has the keys browser and proxy.

Show solution
const config = { browser: 'chromium', retries: 0 };
console.log('browser' in config);
console.log('proxy' in config);
console.log('retries' in config && config.retries === 0);

Output

true
false
true

Explanation: in checks whether a property exists, even when its value is falsy like 0.

18. Spread operatorIntermediate

Merge default and custom settings with the spread operator.

Show solution
const defaults = { browser: 'chromium', retries: 0, headless: true };
const custom = { retries: 2 };
const finalConfig = { ...defaults, ...custom };
console.log(finalConfig);
console.log([...[1, 2], ...[3]]);

Output

{ browser: 'chromium', retries: 2, headless: true }
[ 1, 2, 3 ]

Explanation: spread copies properties or elements. Later properties overwrite earlier ones with the same name.

19. Bitwise check of permission flagsIntermediate

Use bitwise operators to check which permissions a user has.

Show solution
const READ = 1, WRITE = 2, DELETE = 4;
const userPermissions = READ | WRITE;
console.log('Can read:', (userPermissions & READ) !== 0);
console.log('Can write:', (userPermissions & WRITE) !== 0);
console.log('Can delete:', (userPermissions & DELETE) !== 0);

Output

Can read: true
Can write: true
Can delete: false

Explanation: | combines flags into one number and &amp; tests whether a flag is set.

20. Swap numbers with arithmeticIntermediate

Swap two numbers using only arithmetic operators.

Show solution
let a = 8;
let b = 3;
a = a + b;
b = a - b;
a = a - b;
console.log(a, b);

Output

3 8

Explanation: storing the sum lets you recover each original value with subtraction. Destructuring is clearer in real code.

JavaScript Real-World QA Scenario Programs

21. Calculate cart total with taxReal-world

Calculate the total for a cart of 1200 with 18% tax, and round to 2 decimals.

Show solution
const subtotal = 1200;
const taxRate = 0.18;
const tax = subtotal * taxRate;
const total = subtotal + tax;
console.log('Tax:', tax.toFixed(2));
console.log('Total:', total.toFixed(2));

Output

Tax: 216.00
Total: 1416.00

Explanation: multiplication gives the tax, addition gives the total, and toFixed formats money for display.

22. Apply a discountReal-world

Apply a 15% discount to 2499 and print the discount and final price.

Show solution
const price = 2499;
const discountPercent = 15;
const discount = (price * discountPercent) / 100;
const finalPrice = price - discount;
console.log(`Discount: ${discount.toFixed(2)}`);
console.log(`Final price: ${finalPrice.toFixed(2)}`);

Output

Discount: 374.85
Final price: 2124.15

Explanation: percentages are calculated with * and /. Format the results for display.

23. Pass percentage and gradeReal-world

With passed = 47 of total = 52 tests, calculate the pass rate and label it 'Green' (95%+), 'Amber' (80%+) or 'Red'.

Show solution
const passed = 47;
const total = 52;
const rate = (passed / total) * 100;
const label = rate >= 95 ? 'Green' : rate >= 80 ? 'Amber' : 'Red';
console.log(`${rate.toFixed(1)}% - ${label}`);

Output

90.4% - Amber

Explanation: chained ternaries pick one of several labels. For more than three cases, an if/else chain is clearer.

24. Check a value is within rangeReal-world

Check that a response time of 850 ms is between 0 and 1000 ms, and that 1200 ms is not.

Show solution
const MIN = 0, MAX = 1000;
for (const ms of [850, 1200]) {
  const ok = ms >= MIN && ms <= MAX;
  console.log(`${ms} ms within SLA: ${ok}`);
}

Output

850 ms within SLA: true
1200 ms within SLA: false

Explanation: combine two comparisons with &amp;&amp; to test a range.

25. Validate login form fieldsReal-world

A login is valid when the username is not empty and the password has at least 8 characters. Test three cases.

Show solution
const cases = [['qa_user', 'Secret123'], ['', 'Secret123'], ['qa_user', 'short']];
for (const [username, password] of cases) {
  const valid = username.length > 0 && password.length >= 8;
  console.log(`'${username}' / ${password.length} chars -> ${valid ? 'valid' : 'invalid'}`);
}

Output

'qa_user' / 9 chars -> valid
'' / 9 chars -> invalid
'qa_user' / 5 chars -> invalid

Explanation: &amp;&amp; requires every rule to pass. One false condition makes the whole expression false.

26. Decide whether to retry a testReal-world

Retry when the test failed AND attempts are below the limit, OR when the failure was a timeout.

Show solution
const MAX_RETRIES = 2;
const runs = [
  { failed: true, attempts: 1, timeout: false },
  { failed: true, attempts: 2, timeout: false },
  { failed: true, attempts: 3, timeout: true }
];
for (const run of runs) {
  const retry = (run.failed && run.attempts < MAX_RETRIES) || run.timeout;
  console.log(`attempts=${run.attempts} timeout=${run.timeout} -> retry: ${retry}`);
}

Output

attempts=1 timeout=false -> retry: true
attempts=2 timeout=false -> retry: false
attempts=3 timeout=true -> retry: true

Explanation: parentheses make the business rule explicit, because &amp;&amp; binds tighter than ||.

27. Round-robin browser selectionReal-world

Assign 7 test cases to 3 browsers in turn using the modulus operator.

Show solution
const browsers = ['chromium', 'firefox', 'webkit'];
for (let i = 0; i < 7; i++) {
  console.log(`TC-${i + 1} -> ${browsers[i % browsers.length]}`);
}

Output

TC-1 -> chromium
TC-2 -> firefox
TC-3 -> webkit
TC-4 -> chromium
TC-5 -> firefox
TC-6 -> webkit
TC-7 -> chromium

Explanation: i % length cycles through 0, 1, 2, 0, 1, … which is ideal for distributing work.

28. Convert milliseconds to h:m:sReal-world

Convert 3725000 ms into hours, minutes and seconds.

Show solution
const ms = 3725000;
const totalSeconds = Math.floor(ms / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
console.log(`${hours}h ${minutes}m ${seconds}s`);

Output

1h 2m 5s

Explanation: division gives the larger units and % gives what is left over.

29. Compare expected and actual countsReal-world

Compare the expected item count with the count shown in the UI, which is text, and print a clear message.

Show solution
const expectedCount = 3;
const uiText = '3';
const loose = expectedCount == uiText;
const strict = expectedCount === Number(uiText);
console.log('Loose match:', loose);
console.log('Strict match after conversion:', strict);

Output

Loose match: true
Strict match after conversion: true

Explanation: convert UI text explicitly and use ===, so a mismatch in types never hides a real bug.

30. Build a feature-flag decisionReal-world

Show a beta banner when the feature is enabled and the user is either a beta tester or an employee.

Show solution
const users = [
  { name: 'Asha', betaTester: true, employee: false },
  { name: 'Ravi', betaTester: false, employee: false },
  { name: 'Meera', betaTester: false, employee: true }
];
const featureEnabled = true;
for (const u of users) {
  const showBanner = featureEnabled && (u.betaTester || u.employee);
  console.log(u.name, showBanner);
}

Output

Asha true
Ravi false
Meera true

Explanation: grouping the || part with parentheses makes the rule read exactly like the requirement.

31. Average response timeReal-world

Calculate the average of the response times 120, 340, 95 and 410 ms.

Show solution
const times = [120, 340, 95, 410];
let sum = 0;
for (const t of times) sum += t;
const avg = sum / times.length;
console.log('Average:', avg, 'ms');
console.log('Above 200 ms:', avg > 200);

Output

Average: 241.25 ms
Above 200 ms: true

Explanation: += accumulates the total and / divides by the count to get the average.

32. Version comparisonReal-world

Compare two version strings '1.48.2' and '1.50.0' part by part.

Show solution
const current = '1.48.2'.split('.').map(Number);
const required = '1.50.0'.split('.').map(Number);
let result = 0;
for (let i = 0; i < 3 && result === 0; i++) {
  result = current[i] > required[i] ? 1 : current[i] < required[i] ? -1 : 0;
}
console.log(result < 0 ? 'Upgrade needed' : 'Version OK');

Output

Upgrade needed

Explanation: comparing numbers part by part avoids string comparison bugs such as '1.9' &gt; '1.10'.

Keep Practising

JavaScript Type Conversion Practice Programs with Solutions (31 Programs)

Practise JavaScript type conversion with 31 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.

New to this topic? Read the JavaScript Type Conversion lesson first.

JavaScript Beginner Programs

1. String to number with Number()Beginner

Convert the strings '42', '3.14' and '' to numbers and print the results.

Show solution
console.log(Number('42'));
console.log(Number('3.14'));
console.log(Number(''));

Output

42
3.14
0

Explanation: Number() converts a whole string to a number. An empty string becomes 0.

2. Invalid number stringsBeginner

Convert '42px' and 'abc' with Number() and print the results.

Show solution
console.log(Number('42px'));
console.log(Number('abc'));

Output

NaN
NaN

Explanation: Number() returns NaN if any part of the string is not numeric.

3. parseInt and parseFloatBeginner

Read the leading number from '42px' with parseInt and from '3.75 kg' with parseFloat.

Show solution
console.log(parseInt('42px', 10));
console.log(parseFloat('3.75 kg'));
console.log(parseInt('px42', 10));

Output

42
3.75
NaN

Explanation: the parse functions read digits from the start and stop at the first invalid character. If the string does not start with a number, they return NaN.

4. Number to stringBeginner

Convert the number 404 to a string in three different ways and print the types.

Show solution
const code = 404;
const a = String(code);
const b = code.toString();
const c = `${code}`;
console.log(a, b, c);
console.log(typeof a, typeof b, typeof c);

Output

404 404 404
string string string

Explanation: String(), .toString() and template literals all produce a string.

5. Convert to booleanBeginner

Use Boolean() on 0, 1, '', '0' and 'false'.

Show solution
console.log(Boolean(0));
console.log(Boolean(1));
console.log(Boolean(''));
console.log(Boolean('0'));
console.log(Boolean('false'));

Output

false
true
false
true
true

Explanation: any non-empty string is truthy, even '0' and 'false'.

6. Unary plusBeginner

Convert '25' to a number with the unary + operator and add 5.

Show solution
const quantity = '25';
console.log(quantity + 5);
console.log(+quantity + 5);

Output

255
30

Explanation: without conversion + joins strings, giving '255'. Unary + converts the string first.

7. String concatenation coercionBeginner

Print the results of '5' + 3, '5' - 3, '5' * '2' and '10' / '2'.

Show solution
console.log('5' + 3);
console.log('5' - 3);
console.log('5' * '2');
console.log('10' / '2');

Output

53
2
10
5

Explanation: + prefers string concatenation, while -, * and / convert both sides to numbers.

8. Round and format numbersBeginner

Round 19.987 to two decimals as a string and as a number.

Show solution
const amount = 19.987;
const asString = amount.toFixed(2);
const asNumber = Number(asString);
console.log(asString, typeof asString);
console.log(asNumber, typeof asNumber);

Output

19.99 string
19.99 number

Explanation: toFixed returns a string. Wrap it with Number() when you need a number again.

9. Array to stringBeginner

Convert ['smoke', 'regression'] to a string using String() and join(' | ').

Show solution
const tags = ['smoke', 'regression'];
console.log(String(tags));
console.log(tags.join(' | '));

Output

smoke,regression
smoke | regression

Explanation: arrays convert to comma-separated strings. join lets you choose the separator.

10. String to arrayBeginner

Split 'chromium,firefox,webkit' into an array and print its length.

Show solution
const csv = 'chromium,firefox,webkit';
const browsers = csv.split(',');
console.log(browsers);
console.log(browsers.length);

Output

[ 'chromium', 'firefox', 'webkit' ]
3

Explanation: split converts a delimited string into an array of strings.

JavaScript Intermediate Programs

11. Loose vs strict equalityIntermediate

Compare 0 == '', 0 === '', '1' == 1 and null == 0.

Show solution
console.log(0 == '');
console.log(0 === '');
console.log('1' == 1);
console.log(null == 0);

Output

true
false
true
false

Explanation: == converts types before comparing, with some surprising rules. Prefer === in tests.

12. parseInt with a radixIntermediate

Parse '1010' as binary and 'ff' as hexadecimal, then convert 255 back to hex.

Show solution
console.log(parseInt('1010', 2));
console.log(parseInt('ff', 16));
console.log((255).toString(16));

Output

10
255
ff

Explanation: the second argument of parseInt is the base. toString(base) converts the other way.

13. Number() vs parseInt on decimalsIntermediate

Compare Number('12.9'), parseInt('12.9', 10) and Math.trunc(Number('12.9')).

Show solution
console.log(Number('12.9'));
console.log(parseInt('12.9', 10));
console.log(Math.trunc(Number('12.9')));

Output

12.9
12
12

Explanation: parseInt drops the decimal part. Use Number to keep it, or Math.trunc for an explicit integer.

14. Object to JSON and backIntermediate

Convert a test-config object to JSON text and parse it back.

Show solution
const config = { browser: 'chromium', retries: 2, headless: true };
const json = JSON.stringify(config);
console.log(json, typeof json);
const parsed = JSON.parse(json);
console.log(parsed.retries + 1);

Output

{"browser":"chromium","retries":2,"headless":true} string
3

Explanation: JSON.stringify turns data into text, for files or APIs. JSON.parse turns it back into objects with real numbers and booleans.

15. Pretty-print JSONIntermediate

Print an object as indented JSON with two spaces.

Show solution
const result = { test: 'login', status: 'passed' };
console.log(JSON.stringify(result, null, 2));

Output

{
  "test": "login",
  "status": "passed"
}

Explanation: the third argument of JSON.stringify adds indentation, which makes logs easier to read.

16. Values JSON cannot keepIntermediate

Stringify an object containing undefined, a function and NaN, and print the result.

Show solution
const data = { a: undefined, b: () => 1, c: NaN, d: 'ok' };
console.log(JSON.stringify(data));

Output

{"c":null,"d":"ok"}

Explanation: JSON drops undefined and functions, and turns NaN into null.

17. Date to timestamp and ISO stringIntermediate

Create a date from a fixed ISO string and print its timestamp and ISO form.

Show solution
const date = new Date('2026-01-15T10:30:00Z');
console.log(date.getTime());
console.log(date.toISOString());
console.log(new Date(0).toISOString());

Output

1768473000000
2026-01-15T10:30:00.000Z
1970-01-01T00:00:00.000Z

Explanation: getTime() gives milliseconds since 1 January 1970 UTC, and toISOString() gives a standard text format.

18. Object conversion with valueOfIntermediate

Create an object with valueOf and toString, then use it in maths and in a template literal.

Show solution
const price = {
  amount: 499,
  valueOf() { return this.amount; },
  toString() { return `₹${this.amount}`; }
};
console.log(price + 1);
console.log(`${price}`);

Output

500
₹499

Explanation: maths calls valueOf, while template literals call toString.

19. Number checks: isNaN vs Number.isNaNIntermediate

Compare isNaN('abc') with Number.isNaN('abc').

Show solution
console.log(isNaN('abc'));
console.log(Number.isNaN('abc'));
console.log(Number.isNaN(Number('abc')));

Output

true
false
true

Explanation: global isNaN converts its argument first. Number.isNaN only returns true for the actual NaN value.

20. Map and object conversionsIntermediate

Convert an object into a Map and back again.

Show solution
const scores = { login: 95, checkout: 80 };
const map = new Map(Object.entries(scores));
console.log(map.get('checkout'));
const back = Object.fromEntries(map);
console.log(back);

Output

80
{ login: 95, checkout: 80 }

Explanation: Object.entries and Object.fromEntries convert between plain objects and key/value pairs.

JavaScript Real-World QA Scenario Programs

21. Parse a price from page textReal-world

Extract the number from the UI text '₹1,299.50'.

Show solution
const priceText = '₹1,299.50';
const price = Number(priceText.replace(/[^0-9.]/g, ''));
console.log(price);
console.log(price + 100);

Output

1299.5
1399.5

Explanation: remove currency symbols and thousands separators, then convert. UI text is always a string.

22. Sum prices read from the pageReal-world

A test reads cart prices as strings. Convert and sum them.

Show solution
const priceTexts = ['$12.50', '$7.25', '$30.00'];
const total = priceTexts
  .map(text => Number(text.replace('$', '')))
  .reduce((sum, value) => sum + value, 0);
console.log(total.toFixed(2));

Output

49.75

Explanation: summing the raw strings would concatenate them, so convert each to a number first.

23. Read numeric environment variablesReal-world

Convert the environment values '4' and undefined to a worker count with a default of 2.

Show solution
const env = { WORKERS: '4' };
const workers = Number(env.WORKERS ?? 2);
const retries = Number(env.RETRIES ?? 0);
console.log(workers, typeof workers);
console.log(retries);

Output

4 number
0

Explanation: environment variables are always strings or missing. Convert them and provide defaults.

24. Parse a boolean flag safelyReal-world

Turn HEADLESS values such as 'true', 'false', '1' and undefined into booleans.

Show solution
const toBool = value => ['true', '1', 'yes'].includes(String(value).toLowerCase());
console.log(toBool('true'));
console.log(toBool('false'));
console.log(toBool('1'));
console.log(toBool(undefined));

Output

true
false
true
false

Explanation: Boolean('false') is true, so compare against known true values instead.

25. Parse CSV rows into typed objectsReal-world

Convert a CSV line 'qa_user,25,true' into an object with a string, number and boolean.

Show solution
const line = 'qa_user,25,true';
const [username, age, active] = line.split(',');
const user = { username, age: Number(age), active: active === 'true' };
console.log(user);

Output

{ username: 'qa_user', age: 25, active: true }

Explanation: CSV fields are text, so convert each column to the type your test expects.

26. Compare an API number with UI textReal-world

The API returns 1299 and the UI shows '1,299'. Compare them correctly.

Show solution
const apiPrice = 1299;
const uiText = '1,299';
console.log(apiPrice === uiText);
console.log(apiPrice === Number(uiText.replace(/,/g, '')));

Output

false
true

Explanation: normalise the UI text into a number before comparing it with API data.

27. Convert durationsReal-world

Convert a test duration of 125430 ms into minutes and seconds.

Show solution
const durationMs = 125430;
const totalSeconds = Math.floor(durationMs / 1000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
console.log(`${minutes}m ${String(seconds).padStart(2, '0')}s`);

Output

2m 05s

Explanation: integer division with Math.floor and % converts a raw number into a readable duration.

28. Read numbers from a sentenceReal-world

Extract all numbers from 'Passed 45 of 50 tests in 12.5 seconds'.

Show solution
const summary = 'Passed 45 of 50 tests in 12.5 seconds';
const numbers = summary.match(/\d+(\.\d+)?/g).map(Number);
console.log(numbers);
console.log(numbers[0] / numbers[1]);

Output

[ 45, 50, 12.5 ]
0.9

Explanation: match with a global regular expression finds every number as a string, and map(Number) converts them.

29. Normalise mixed input typesReal-world

A form sends quantities as 5, '7', '' and null. Convert them to numbers, treating empty values as 0.

Show solution
const inputs = [5, '7', '', null, '3'];
const quantities = inputs.map(value => (value === '' || value == null ? 0 : Number(value)));
console.log(quantities);
console.log(quantities.reduce((a, b) => a + b, 0));

Output

[ 5, 7, 0, 0, 3 ]
15

Explanation: decide explicitly how empty values convert, rather than relying on implicit coercion.

30. Format a number as currency textReal-world

Format 1234567.891 as a US dollar amount and an Indian rupee amount.

Show solution
const amount = 1234567.891;
console.log(amount.toLocaleString('en-US', { style: 'currency', currency: 'USD' }));
console.log(amount.toLocaleString('en-IN', { style: 'currency', currency: 'INR' }));

Output

$1,234,567.89
₹12,34,567.89

Explanation: toLocaleString converts numbers into locale-aware text, which is useful when asserting formatted prices.

31. Query string to objectReal-world

Convert the query string '?page=2&amp;sort=price&amp;inStock=true' into an object with typed values.

Show solution
const params = new URLSearchParams('?page=2&sort=price&inStock=true');
const query = {
  page: Number(params.get('page')),
  sort: params.get('sort'),
  inStock: params.get('inStock') === 'true'
};
console.log(query);

Output

{ page: 2, sort: 'price', inStock: true }

Explanation: URLSearchParams returns every value as a string, so convert numbers and booleans yourself.

Keep Practising

JavaScript Data Types Practice Programs with Solutions (31 Programs)

Practise JavaScript data types with 31 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.

New to this topic? Read the JavaScript Data Types lesson first.

JavaScript Beginner Programs

1. Print the type of each primitiveBeginner

Use typeof to print the type of a string, number, boolean, undefined, bigint and symbol.

Show solution
console.log(typeof 'Playwright');
console.log(typeof 42);
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof 10n);
console.log(typeof Symbol('id'));

Output

string
number
boolean
undefined
bigint
symbol

Explanation: typeof returns a string naming the type. These six, plus null, are JavaScript’s primitive types.

2. typeof nullBeginner

Print typeof null and explain the result in a comment.

Show solution
const value = null;
console.log(typeof value);
console.log(value === null);

Output

object
true

Explanation: typeof null returns 'object' because of an old bug kept for compatibility. Check for null with === null.

3. Arrays and functions with typeofBeginner

Print typeof for an array, an object and a function.

Show solution
console.log(typeof ['chromium', 'firefox']);
console.log(typeof { retries: 2 });
console.log(typeof function login() {});

Output

object
object
function

Explanation: arrays are objects, so typeof returns 'object'. Functions are a special case and return 'function'.

4. Check for an arrayBeginner

Use Array.isArray to tell an array apart from a plain object.

Show solution
const browsers = ['chromium', 'webkit'];
const config = { browser: 'chromium' };
console.log(Array.isArray(browsers));
console.log(Array.isArray(config));

Output

true
false

Explanation: Array.isArray is the reliable array check, because typeof returns 'object' for both.

5. Integer or decimalBeginner

Check whether 10, 10.5 and -3 are integers.

Show solution
console.log(Number.isInteger(10));
console.log(Number.isInteger(10.5));
console.log(Number.isInteger(-3));

Output

true
false
true

Explanation: JavaScript has one number type for integers and decimals. Number.isInteger checks for whole numbers.

6. NaN is a numberBeginner

Divide a string by a number, then print the result, its type and whether it is NaN.

Show solution
const result = 'abc' / 2;
console.log(result);
console.log(typeof result);
console.log(Number.isNaN(result));

Output

NaN
number
true

Explanation: invalid maths produces NaN (“Not a Number”), which is still of type number.

7. InfinityBeginner

Print the results of dividing 1 by 0 and -1 by 0, and their type.

Show solution
console.log(1 / 0);
console.log(-1 / 0);
console.log(typeof Infinity);

Output

Infinity
-Infinity
number

Explanation: dividing by zero gives Infinity or -Infinity instead of an error.

8. Boolean values from comparisonsBeginner

Store the results of three comparisons in variables and print them with their type.

Show solution
const isPassed = 85 >= 70;
const isEmpty = ''.length === 0;
const isAdmin = 'viewer' === 'admin';
console.log(isPassed, isEmpty, isAdmin);
console.log(typeof isPassed);

Output

true true false
boolean

Explanation: comparison operators always produce a boolean, true or false.

9. null vs undefinedBeginner

Compare null and undefined with == and ===.

Show solution
let notAssigned;
const emptyValue = null;
console.log(notAssigned == emptyValue);
console.log(notAssigned === emptyValue);

Output

true
false

Explanation: loose equality treats null and undefined as equal. Strict equality also compares types, so they differ.

10. String length and charactersBeginner

Print the length of 'Playwright', its first character and its last character.

Show solution
const tool = 'Playwright';
console.log(tool.length);
console.log(tool[0]);
console.log(tool[tool.length - 1]);

Output

10
P
t

Explanation: strings have a length property and characters can be read by index, starting at 0.

JavaScript Intermediate Programs

11. Floating-point precisionIntermediate

Print 0.1 + 0.2, compare it with 0.3, then compare safely using a tolerance.

Show solution
const sum = 0.1 + 0.2;
console.log(sum);
console.log(sum === 0.3);
console.log(Math.abs(sum - 0.3) < Number.EPSILON);

Output

0.30000000000000004
false
true

Explanation: decimals are stored in binary floating point, so some sums are slightly off. Compare with a tolerance instead.

12. Safe integer limitsIntermediate

Print the largest safe integer and show that adding 1 and 2 to it gives the same result.

Show solution
const max = Number.MAX_SAFE_INTEGER;
console.log(max);
console.log(max + 1 === max + 2);
console.log(Number.isSafeInteger(max + 1));

Output

9007199254740991
true
false

Explanation: beyond 2^53 − 1, numbers lose precision, so different integers can become equal.

13. BigInt for large IDsIntermediate

Store a large order ID as a BigInt, add 1 and print it.

Show solution
const orderId = 9007199254740993n;
const nextId = orderId + 1n;
console.log(nextId);
console.log(typeof nextId);

Output

9007199254740994n
bigint

Explanation: BigInt (numbers ending in n) stores arbitrarily large integers exactly. You cannot mix BigInt and number in maths.

14. Mixing BigInt and numberIntermediate

Try adding a BigInt to a number and print the error message, then do it correctly.

Show solution
try {
  console.log(10n + 5);
} catch (error) {
  console.log(error.name);
}
console.log(10n + BigInt(5));

Output

TypeError
15n

Explanation: mixing types throws a TypeError. Convert explicitly with BigInt() or Number().

15. Symbols are uniqueIntermediate

Create two symbols with the same description and compare them.

Show solution
const id1 = Symbol('testId');
const id2 = Symbol('testId');
console.log(id1 === id2);
console.log(id1.description);

Output

false
testId

Explanation: every Symbol() call creates a unique value, even with the same description.

16. Primitives are immutableIntermediate

Try to change the first character of a string and print it.

Show solution
let browser = 'chromium';
browser[0] = 'C';
console.log(browser);
browser = browser[0].toUpperCase() + browser.slice(1);
console.log(browser);

Output

chromium
Chromium

Explanation: you cannot change a string in place. Methods return a new string, which you assign back to the variable.

17. Truthy and falsy valuesIntermediate

Print whether each value in a list is truthy or falsy.

Show solution
const samples = [
  [0, '0'], ['', "''"], ['qa', "'qa'"], [null, 'null'], [undefined, 'undefined'],
  [NaN, 'NaN'], [[], '[]'], [{}, '{}'], [-1, '-1']
];
for (const [value, label] of samples) {
  console.log(label, '->', value ? 'truthy' : 'falsy');
}

Output

0 -> falsy
'' -> falsy
'qa' -> truthy
null -> falsy
undefined -> falsy
NaN -> falsy
[] -> truthy
{} -> truthy
-1 -> truthy

Explanation: 0, '', null, undefined, NaN and false are falsy. Empty arrays and objects are truthy.

18. Detect the real typeIntermediate

Write a function that returns 'null', 'array' or the typeof result, and test it with several values.

Show solution
function getType(value) {
  if (value === null) return 'null';
  if (Array.isArray(value)) return 'array';
  return typeof value;
}
console.log(getType(null));
console.log(getType([1, 2]));
console.log(getType({}));
console.log(getType('text'));

Output

null
array
object
string

Explanation: combining checks fixes the two surprises of typeof: null and arrays.

19. Object.prototype.toString type checkIntermediate

Print the internal type tag of a date, an array, null and a regular expression.

Show solution
const tag = value => Object.prototype.toString.call(value);
console.log(tag(new Date(0)));
console.log(tag([]));
console.log(tag(null));
console.log(tag(/test/));

Output

[object Date]
[object Array]
[object Null]
[object RegExp]

Explanation: Object.prototype.toString returns a precise tag such as [object Date], useful for robust type checks.

20. Compare by value vs by referenceIntermediate

Compare two identical arrays with ===, then compare their JSON strings.

Show solution
const expected = ['login', 'logout'];
const actual = ['login', 'logout'];
console.log(expected === actual);
console.log(JSON.stringify(expected) === JSON.stringify(actual));

Output

false
true

Explanation: === compares object references, not contents. For simple data, comparing JSON strings checks the values.

JavaScript Real-World QA Scenario Programs

21. Validate API field typesReal-world

Check that each field in an API user object has the expected type and print any mismatch.

Show solution
const user = { id: 101, name: 'Asha', active: 'yes', tags: ['qa'] };
const schema = { id: 'number', name: 'string', active: 'boolean', tags: 'array' };
for (const [field, expected] of Object.entries(schema)) {
  const value = user[field];
  const actual = Array.isArray(value) ? 'array' : typeof value;
  if (actual !== expected) console.log(`${field}: expected ${expected}, got ${actual}`);
}
console.log('Type check finished');

Output

active: expected boolean, got string
Type check finished

Explanation: simple schema checks catch API contract bugs early, such as a boolean sent as the string 'yes'.

22. Count values by typeReal-world

Count how many values of each type a response array contains.

Show solution
const response = [1, 'two', 3, null, true, 'six', undefined, 8];
const counts = {};
for (const value of response) {
  const type = value === null ? 'null' : typeof value;
  counts[type] = (counts[type] || 0) + 1;
}
console.log(counts);

Output

{ number: 3, string: 2, null: 1, boolean: 1, undefined: 1 }

Explanation: grouping by type helps spot unexpected data, such as nulls in a numeric column.

23. Check for missing valuesReal-world

Report which form fields are empty, null or undefined.

Show solution
const form = { firstName: 'Ravi', lastName: '', email: null, phone: undefined, city: 'Pune' };
const missing = Object.keys(form).filter(key => form[key] === '' || form[key] == null);
console.log('Missing fields:', missing.join(', '));

Output

Missing fields: lastName, email, phone

Explanation: == null matches both null and undefined, and === '' catches empty strings.

24. Verify a price is a valid numberReal-world

Check a list of prices and print whether each one is a finite, non-negative number.

Show solution
const prices = [499, -10, NaN, Infinity, 0, '299'];
for (const price of prices) {
  const valid = typeof price === 'number' && Number.isFinite(price) && price >= 0;
  console.log(String(price), valid ? 'valid' : 'invalid');
}

Output

499 valid
-10 invalid
NaN invalid
Infinity invalid
0 valid
299 invalid

Explanation: Number.isFinite rejects NaN and Infinity, and the typeof check rejects numbers stored as strings.

25. Optional response fieldsReal-world

Read a nested optional field safely and fall back to a default.

Show solution
const responseA = { user: { address: { city: 'Mumbai' } } };
const responseB = { user: {} };
console.log(responseA.user.address?.city ?? 'Unknown');
console.log(responseB.user.address?.city ?? 'Unknown');

Output

Mumbai
Unknown

Explanation: optional chaining returns undefined instead of throwing when a property is missing, and ?? supplies a default.

26. Identify boolean-like stringsReal-world

Convert the CSV values 'true', 'false' and 'TRUE' to real booleans and print their type.

Show solution
const csvValues = ['true', 'false', 'TRUE'];
for (const text of csvValues) {
  const bool = text.toLowerCase() === 'true';
  console.log(text, '->', bool, typeof bool);
}

Output

true -> true boolean
false -> false boolean
TRUE -> true boolean

Explanation: Boolean('false') would be true because the string is non-empty, so compare the text instead.

27. Detect empty arrays and objectsReal-world

Write checks that report whether an API returned an empty list or an empty object.

Show solution
const isEmptyArray = value => Array.isArray(value) && value.length === 0;
const isEmptyObject = value => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === 0;
console.log(isEmptyArray([]), isEmptyArray([1]));
console.log(isEmptyObject({}), isEmptyObject({ id: 1 }));

Output

true false
true false

Explanation: empty arrays and objects are truthy, so you must check length or Object.keys explicitly.

28. Copy test data safelyReal-world

Make a deep copy of nested test data with structuredClone, change the copy and show the original is unchanged.

Show solution
const baseUser = { name: 'Asha', roles: ['viewer'] };
const adminUser = structuredClone(baseUser);
adminUser.roles.push('admin');
console.log(baseUser.roles);
console.log(adminUser.roles);

Output

[ 'viewer' ]
[ 'viewer', 'admin' ]

Explanation: structuredClone copies nested objects too, so changing the copy does not leak into shared test data.

29. Spread creates a shallow copyReal-world

Copy an object with spread, change a nested array and observe the side effect.

Show solution
const original = { name: 'cart', items: ['pen'] };
const copy = { ...original };
copy.name = 'wishlist';
copy.items.push('book');
console.log(original.name, original.items);

Output

cart [ 'pen', 'book' ]

Explanation: spread copies only the top level. Nested arrays and objects are still shared between the copies.

30. Summarise data types in test dataReal-world

Print a one-line summary of the type of each property in a test case object.

Show solution
const testCase = { id: 'TC-101', priority: 1, automated: true, tags: ['smoke'], owner: null };
const summary = Object.entries(testCase)
  .map(([key, value]) => `${key}:${value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value}`)
  .join(' | ');
console.log(summary);

Output

id:string | priority:number | automated:boolean | tags:array | owner:null

Explanation: a quick type summary is handy when debugging data loaded from JSON or CSV files.

31. Validate a status code typeReal-world

An API returns its status as a string. Show why === comparison with a number fails, and fix it.

Show solution
const response = { status: '200' };
console.log(response.status === 200);
console.log(Number(response.status) === 200);
console.log(typeof response.status);

Output

false
true
string

Explanation: strict equality compares types, so '200' === 200 is false. Convert explicitly before comparing.

Keep Practising

JavaScript Variables Practice Programs with Solutions (32 Programs)

Practise JavaScript variables with 32 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.

New to this topic? Read the JavaScript Variables lesson first.

JavaScript Beginner Programs

1. Declare and print variablesBeginner

Declare a variable testerName with your name and a variable experienceYears with a number, then print both.

Show solution
let testerName = 'Asha';
let experienceYears = 3;
console.log('Tester:', testerName);
console.log('Experience (years):', experienceYears);

Output

Tester: Asha
Experience (years): 3

Explanation: let declares a variable that holds a value. console.log prints its arguments separated by a space.

2. Reassign a let variableBeginner

Create browser with the value 'chromium', print it, change it to 'firefox' and print it again.

Show solution
let browser = 'chromium';
console.log('Before:', browser);
browser = 'firefox';
console.log('After:', browser);

Output

Before: chromium
After: firefox

Explanation: variables declared with let can be reassigned. The second assignment replaces the old value.

3. Constants cannot be reassignedBeginner

Store a base URL in a const, then try to reassign it inside try/catch and print the error message.

Show solution
const BASE_URL = 'https://qa.example.com';
try {
  BASE_URL = 'https://prod.example.com';
} catch (error) {
  console.log('Error:', error.message);
}
console.log('BASE_URL is still', BASE_URL);

Output

Error: Assignment to constant variable.
BASE_URL is still https://qa.example.com

Explanation: a const binding cannot be reassigned, so the assignment throws a TypeError. The original value stays unchanged.

4. Swap two variables with a temporary variableBeginner

Swap the values of a = 10 and b = 20 using a third variable and print them before and after.

Show solution
let a = 10;
let b = 20;
console.log('Before swap: a =', a, 'b =', b);
let temp = a;
a = b;
b = temp;
console.log('After swap: a =', a, 'b =', b);

Output

Before swap: a = 10 b = 20
After swap: a = 20 b = 10

Explanation: the temporary variable keeps the first value safe while it is overwritten.

5. Swap two variables with destructuringBeginner

Swap first = 'login' and second = 'logout' without a temporary variable.

Show solution
let first = 'login';
let second = 'logout';
[first, second] = [second, first];
console.log(first, second);

Output

logout login

Explanation: array destructuring builds a temporary array [second, first] and unpacks it back into the two variables in one step.

6. Declare several variables in one statementBeginner

Declare passed, failed and skipped test counts in a single let statement and print the total.

Show solution
let passed = 42, failed = 3, skipped = 5;
let total = passed + failed + skipped;
console.log('Total tests:', total);

Output

Total tests: 50

Explanation: one let can declare several comma-separated variables. Readability usually favours one per line in real projects.

7. Uninitialised variableBeginner

Declare result without a value and print it and its type.

Show solution
let result;
console.log(result);
console.log(typeof result);

Output

undefined
undefined

Explanation: a declared but unassigned variable holds undefined, whose type is also 'undefined'.

8. Build a message with a template literalBeginner

Use variables user = 'qa_admin' and role = 'Admin' to print Logged in as qa_admin (Admin).

Show solution
const user = 'qa_admin';
const role = 'Admin';
const message = `Logged in as ${user} (${role})`;
console.log(message);

Output

Logged in as qa_admin (Admin)

Explanation: template literals (backticks) insert variable values with ${...}.

9. Increment a counterBeginner

Start retryCount at 0, increase it three times using different syntax and print it after each step.

Show solution
let retryCount = 0;
retryCount = retryCount + 1;
console.log(retryCount);
retryCount += 1;
console.log(retryCount);
retryCount++;
console.log(retryCount);

Output

1
2
3

Explanation: x = x + 1, x += 1 and x++ all add one to a let variable.

10. Valid variable namesBeginner

Create variables named with camelCase, a leading underscore and a dollar sign, then print them together.

Show solution
const firstName = 'Ravi';
const _internalId = 101;
const $price = 499;
console.log(firstName, _internalId, $price);

Output

Ravi 101 499

Explanation: names may start with a letter, _ or $, and must not start with a digit. camelCase is the usual convention.

JavaScript Intermediate Programs

11. Block scope with letIntermediate

Declare status outside an if block and a different status inside it. Print both to show they are separate.

Show solution
let status = 'outer';
if (true) {
  let status = 'inner';
  console.log('Inside block:', status);
}
console.log('Outside block:', status);

Output

Inside block: inner
Outside block: outer

Explanation: let is block-scoped, so the inner status exists only inside the braces and does not affect the outer one.

12. var ignores block scopeIntermediate

Repeat the previous program using var and observe the difference.

Show solution
var status = 'outer';
if (true) {
  var status = 'inner';
  console.log('Inside block:', status);
}
console.log('Outside block:', status);

Output

Inside block: inner
Outside block: inner

Explanation: var is function-scoped, so both declarations refer to the same variable and the block overwrites it.

13. Hoisting with varIntermediate

Print a var variable before the line that declares it.

Show solution
console.log('Before declaration:', environment);
var environment = 'staging';
console.log('After declaration:', environment);

Output

Before declaration: undefined
After declaration: staging

Explanation: var declarations are hoisted and initialised with undefined, so the first log prints undefined instead of throwing.

14. Temporal dead zone with letIntermediate

Access a let variable before its declaration inside try/catch and print the error name.

Show solution
try {
  console.log(timeout);
  let timeout = 30000;
} catch (error) {
  console.log(error.name + ': ' + error.message);
}

Output

ReferenceError: Cannot access 'timeout' before initialization

Explanation: let and const are hoisted but not initialised. Using them before the declaration throws a ReferenceError (the temporal dead zone).

15. const object can still changeIntermediate

Store test settings in a const object, change one property and print the object.

Show solution
const settings = { headless: true, retries: 0 };
settings.retries = 2;
console.log(settings);

Output

{ headless: true, retries: 2 }

Explanation: const stops reassignment of the variable, not changes to the object it points to.

16. Freeze a configuration objectIntermediate

Freeze a config object, try to change it and print it to show the change was ignored.

Show solution
const config = Object.freeze({ browser: 'chromium', workers: 4 });
config.workers = 8;
console.log(config.workers);
console.log(Object.isFrozen(config));

Output

4
true

Explanation: Object.freeze makes properties read-only. In non-strict code the assignment is silently ignored.

17. Loop variable scope: let vs varIntermediate

Collect functions in a loop using let and using var, then call them to see which values they remember.

Show solution
const withLet = [];
for (let i = 0; i < 3; i++) withLet.push(() => i);
const withVar = [];
for (var j = 0; j < 3; j++) withVar.push(() => j);
console.log('let:', withLet.map(f => f()));
console.log('var:', withVar.map(f => f()));

Output

let: [ 0, 1, 2 ]
var: [ 3, 3, 3 ]

Explanation: let creates a new binding for each loop iteration. var shares one variable, so every function sees its final value 3.

18. Shadowing in nested blocksIntermediate

Use the same name level in three nested scopes and print it from each one.

Show solution
const level = 'file';
{
  const level = 'block';
  {
    const level = 'nested block';
    console.log(level);
  }
  console.log(level);
}
console.log(level);

Output

nested block
block
file

Explanation: an inner declaration shadows outer ones with the same name. Each scope sees its nearest declaration.

19. Variables copy primitives by valueIntermediate

Copy a number into another variable, change the copy and print both.

Show solution
let originalTimeout = 5000;
let copiedTimeout = originalTimeout;
copiedTimeout = 10000;
console.log('original:', originalTimeout);
console.log('copy:', copiedTimeout);

Output

original: 5000
copy: 10000

Explanation: primitives such as numbers are copied by value, so changing the copy does not affect the original.

20. Variables share objects by referenceIntermediate

Assign an object to a second variable, change it through the second variable and print the first.

Show solution
const user = { name: 'Asha', active: true };
const sameUser = user;
sameUser.active = false;
console.log(user.active);
console.log(user === sameUser);

Output

false
true

Explanation: both variables point to the same object, so a change through either one is visible through both.

JavaScript Real-World QA Scenario Programs

21. Store environment URLsReal-world

Store base URLs for qa, staging and prod in constants, pick one with a selectedEnv variable and print the login URL.

Show solution
const QA_URL = 'https://qa.shop.test';
const STAGING_URL = 'https://staging.shop.test';
const PROD_URL = 'https://shop.test';
const selectedEnv = 'staging';
const baseUrl = selectedEnv === 'qa' ? QA_URL : selectedEnv === 'staging' ? STAGING_URL : PROD_URL;
const loginUrl = `${baseUrl}/login`;
console.log(loginUrl);

Output

https://staging.shop.test/login

Explanation: constants keep fixed values in one place, and a single variable decides which environment the test uses.

22. Build unique test dataReal-world

Create a unique email for a sign-up test using a fixed runId variable and a username prefix.

Show solution
const prefix = 'qa.user';
const runId = 1730275200;
const email = `${prefix}+${runId}@example.com`;
console.log(email);

Output

qa.user+1730275200@example.com

Explanation: combining a stable prefix with a run ID gives unique but readable test data. In real tests the ID could come from Date.now().

23. Count test resultsReal-world

Use counter variables to tally the statuses ['passed', 'failed', 'passed', 'skipped', 'passed'].

Show solution
const statuses = ['passed', 'failed', 'passed', 'skipped', 'passed'];
let passed = 0, failed = 0, skipped = 0;
for (const status of statuses) {
  if (status === 'passed') passed++;
  else if (status === 'failed') failed++;
  else skipped++;
}
console.log(`Passed: ${passed}, Failed: ${failed}, Skipped: ${skipped}`);

Output

Passed: 3, Failed: 1, Skipped: 1

Explanation: counters declared with let are updated inside the loop. The loop variable status is a fresh const each time.

24. Calculate a pass percentageReal-world

With total = 80 and failed = 6, calculate and print the pass percentage rounded to one decimal place.

Show solution
const total = 80;
const failed = 6;
const passed = total - failed;
const passRate = (passed / total) * 100;
console.log(`Pass rate: ${passRate.toFixed(1)}%`);

Output

Pass rate: 92.5%

Explanation: intermediate variables like passed make the calculation readable. toFixed(1) formats the result.

25. Default timeout with fallbackReal-world

A variable customTimeout may be undefined. Use ?? to fall back to a default of 30000 ms and print the timeout used in both cases.

Show solution
const DEFAULT_TIMEOUT = 30000;
let customTimeout;
console.log('Timeout used:', customTimeout ?? DEFAULT_TIMEOUT);
customTimeout = 60000;
console.log('Timeout used:', customTimeout ?? DEFAULT_TIMEOUT);

Output

Timeout used: 30000
Timeout used: 60000

Explanation: ?? returns the right side only when the left side is null or undefined, which makes it ideal for optional settings.

26. Track login attemptsReal-world

Simulate three failed login attempts with a let counter and lock the account when it reaches MAX_ATTEMPTS = 3.

Show solution
const MAX_ATTEMPTS = 3;
let attempts = 0;
let locked = false;
for (let i = 1; i <= 3; i++) {
  attempts++;
  console.log(`Attempt ${attempts} failed`);
  if (attempts === MAX_ATTEMPTS) locked = true;
}
console.log('Account locked:', locked);

Output

Attempt 1 failed
Attempt 2 failed
Attempt 3 failed
Account locked: true

Explanation: a constant holds the business rule and let variables track state that changes during the scenario.

27. Build a test report lineReal-world

Store the test name, duration in milliseconds and status in variables, then print one formatted report line with the duration in seconds.

Show solution
const testName = 'Checkout with saved card';
const durationMs = 2345;
const status = 'PASSED';
const durationSec = (durationMs / 1000).toFixed(2);
console.log(`[${status}] ${testName} (${durationSec}s)`);

Output

[PASSED] Checkout with saved card (2.35s)

Explanation: separate variables for each piece of data keep the formatting step simple and easy to change.

28. Running cart totalReal-world

Add item prices 499, 1299 and 250 to a running cartTotal, printing the total after each item.

Show solution
let cartTotal = 0;
cartTotal += 499;
console.log('After item 1:', cartTotal);
cartTotal += 1299;
console.log('After item 2:', cartTotal);
cartTotal += 250;
console.log('After item 3:', cartTotal);

Output

After item 1: 499
After item 2: 1798
After item 3: 2048

Explanation: += updates the running total in place, which mirrors how a test checks a cart after each step.

29. Mask a password before loggingReal-world

Store a password in a variable and log a masked version that shows only the last two characters.

Show solution
const password = 'Secr3t!Pass';
const masked = '*'.repeat(password.length - 2) + password.slice(-2);
console.log('Password used:', masked);

Output

Password used: *********ss

Explanation: never log real secrets. A derived variable holds a safe version for logs and reports.

30. Read settings with fallbacksReal-world

Given envVars = { BASE_URL: 'https://qa.app.test' }, read BASE_URL and WORKERS into variables, defaulting WORKERS to 2.

Show solution
const envVars = { BASE_URL: 'https://qa.app.test' };
const baseUrl = envVars.BASE_URL ?? 'http://localhost:3000';
const workers = Number(envVars.WORKERS ?? 2);
console.log('baseUrl:', baseUrl);
console.log('workers:', workers);

Output

baseUrl: https://qa.app.test
workers: 2

Explanation: tests often read process.env, where values may be missing. Defaults keep the run predictable.

31. Destructure test data into variablesReal-world

Unpack username, password and an optional role (default 'viewer') from a test-data object.

Show solution
const testUser = { username: 'qa_tester', password: 'P@ss123' };
const { username, password, role = 'viewer' } = testUser;
console.log(username, role);
console.log('Password length:', password.length);

Output

qa_tester viewer
Password length: 7

Explanation: object destructuring creates several variables at once and can supply defaults for missing properties.

32. Rename while destructuringReal-world

An API returns { id: 7, full_name: 'Neha Sharma' }. Store the values in camelCase variables userId and fullName.

Show solution
const apiUser = { id: 7, full_name: 'Neha Sharma' };
const { id: userId, full_name: fullName } = apiUser;
console.log(`User #${userId}: ${fullName}`);

Output

User #7: Neha Sharma

Explanation: property: newName in destructuring renames a value, which keeps your code in camelCase even when an API uses snake_case.

Keep Practising