PlayForge
← Course

2. Decisions and Loops

Make code choose with if and repeat with loops, the way a test checks and retries.

5m read5m in total

Chapter film (about 7m) is coming. The written chapter below is complete.

Checkpoint 1

Control Flow & Loops

In plain English. Control flow is how a program decides what to do next, and how many times. Tests do this constantly: if the status code is 200, carry on; if it is 404, report a missing page; for every row in a table, check the price. if and switch choose between paths. Loops repeat a step, either a set number of times or once for each item in a list. To iterate means to go through a collection one item at a time. An object is a set of named values, like a user record with a name and a role; each name is called a key. You will meet one loop for lists and a different one for an object's keys.

JavaScript gives you if, else if and else, the ternary operator (condition ? trueValue : falseValue), and a switch statement. switch uses strict equality (===) for its comparisons under the hood.

The classic for loop (for (let i = 0; i < 10; i++)), while loop, and do...while loop are all available, as are the break and continue keywords. Be mindful of scope: declaring loop variables with var leaks them outside the loop block, which is why let is strongly preferred for loop counters.

While the classic for loop is useful, JavaScript provides a more elegant way to iterate over iterable objects (like arrays or strings) using the for...of loop, which hands you each value directly with no index to manage.

JavaScript also has a for...in loop. This is specifically used to iterate over the enumerable string properties (keys) of an object. Do not use for...in to iterate over arrays, as it iterates over indices as strings and can include inherited properties or have unexpected order. Stick to for...of for arrays, and for...in for inspecting object keys.

javascript
const status = 200; if (status === 200) { console.log('Success!'); } else if (status === 404) { console.log('Not Found'); } else { console.log('Unknown error'); } const action = 'START'; switch (action) { case 'START': console.log('Starting...'); break; default: console.log('Idle'); } // for...of (iterates values directly) const fruits = ['apple', 'banana', 'cherry']; for (const fruit of fruits) { console.log('Fruit:', fruit); } // for...in (for object properties) const user = { name: 'Jatin', role: 'Developer' }; for (const key in user) { console.log(`Key: ${key}, Value: ${user[key]}`); }

Sign in to track your progress

Practice set

Practice and interview questions: JavaScript Basics

Welcome to your first set of JavaScript practice exercises. JavaScript is dynamically typed and interpreted: nothing checks types before the code runs, so a misspelled property name surfaces as a runtime surprise rather than a build failure. The discipline has to come from naming and structure instead.

In this chapter, we focus on rebuilding your coding muscles with basic JavaScript syntax: variables, strings, numbers, control flow, and error handling. We've themed these challenges around common automation scenarios, such as parsing strings from web elements and handling unexpected application states.

Treat these exercises like competitive coding problems. Try to solve them efficiently, considering edge cases like null, undefined, or malformed strings. Remember that in JS, == does type coercion, whereas === does strict equality checking (which is usually what you want).

Coding Exercises

  1. Extract Domain (Easy) Problem: Write a function extractDomain(email) that takes an email string and returns the domain part. If the email is invalid (no @), throw an Error. Hint: Use String.prototype.split() or indexOf().

  2. Status Code FizzBuzz (Easy) Problem: Write a function checkStatus(code) that takes an HTTP status code. Return "Success" for 200-299, "Redirect" for 300-399, "Client Error" for 400-499, and "Server Error" for 500-599. Return "Unknown" otherwise. Hint: Use an if/else if chain or a switch statement with true as the expression.

  3. Parse UI Price (Medium) Problem: You scrape a price from a UI: "Total: $1,234.56 USD". Write parsePrice(text) to extract the numeric value 1234.56 as a float. Hint: Use RegEx or string replacement (replace) to remove non-numeric characters before using parseFloat().

  4. Locator Strategy Fallback (Medium) Problem: Write a function findLocator(locators) that takes an array of locator strings. Return the first one that does NOT start with "//" (preferring CSS over XPath). If all are XPath, return the first one. Hint: A simple for loop or for...of loop will do. This is a classic array traversal.

  5. Safe Element Text Extractor (Medium) Problem: Write a function getTextSafe(element) that takes an object. If the object has a text property, return it trimmed. If it is null, undefined, or lacks the property, return "". Catch any TypeErrors if they occur. Hint: Use optional chaining (?.) or a try/catch block. JS throws a TypeError if you read a property of undefined.

Interview Questions

  1. What is the difference between var, let, and const? Answer: var is function-scoped and hoisted with undefined. let and const are block-scoped and are hoisted but remain in the Temporal Dead Zone until initialized. const prevents reassignment, though objects declared with const can still be mutated.

  2. Why should you use === instead of ==? Answer: == performs type coercion (e.g., "1" == 1 is true). === checks both value and type, preventing unexpected bugs.

  3. What is the difference between null and undefined? Answer: undefined means a variable has been declared but not assigned a value. null is an explicit assignment representing "no value".

  4. How do you check if a variable is an array? Answer: Use Array.isArray(variable). typeof will just return "object".

  5. What is NaN and how do you check for it? Answer: NaN stands for Not-a-Number, representing an invalid mathematical operation. Check it using Number.isNaN(value). Interestingly, typeof NaN returns "number".

  6. Is try/catch ever mandatory in JavaScript? Answer: No. JavaScript has no checked exceptions — every error is unchecked, and nothing forces you to use try/catch. You can throw any type (even strings), though throwing Error objects is best practice.

  7. What happens if you omit the return statement in a function? Answer: The function implicitly returns undefined.

  8. Write a quick script to reverse a string. Answer: const reverseStr = str => str.split('').reverse().join('');

javascript
// Exercise 1: Extract Domain function extractDomain(email) { if (!email || !email.includes('@')) { throw new Error('Invalid email'); } return email.split('@')[1]; } console.log(extractDomain('tester@playwright.dev')); // Expected: playwright.dev try { extractDomain('invalid-email'); } catch (e) { console.log('Caught error:', e.message); // Expected: Invalid email }

Sign in to track your progress