2. Decisions and Loops
Make code choose with if and repeat with loops, the way a test checks and retries.
Chapter film (about 7m) is coming. The written chapter below is complete.
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.
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 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
-
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: UseString.prototype.split()orindexOf(). -
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 anif/else ifchain or aswitchstatement withtrueas the expression. -
Parse UI Price (Medium) Problem: You scrape a price from a UI:
"Total: $1,234.56 USD". WriteparsePrice(text)to extract the numeric value1234.56as a float. Hint: Use RegEx or string replacement (replace) to remove non-numeric characters before usingparseFloat(). -
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 simpleforloop orfor...ofloop will do. This is a classic array traversal. -
Safe Element Text Extractor (Medium) Problem: Write a function
getTextSafe(element)that takes an object. If the object has atextproperty, return it trimmed. If it isnull,undefined, or lacks the property, return"". Catch any TypeErrors if they occur. Hint: Use optional chaining (?.) or atry/catchblock. JS throws aTypeErrorif you read a property ofundefined.
Interview Questions
-
What is the difference between
var,let, andconst? Answer:varis function-scoped and hoisted withundefined.letandconstare block-scoped and are hoisted but remain in the Temporal Dead Zone until initialized.constprevents reassignment, though objects declared withconstcan still be mutated. -
Why should you use
===instead of==? Answer:==performs type coercion (e.g.,"1" == 1is true).===checks both value and type, preventing unexpected bugs. -
What is the difference between
nullandundefined? Answer:undefinedmeans a variable has been declared but not assigned a value.nullis an explicit assignment representing "no value". -
How do you check if a variable is an array? Answer: Use
Array.isArray(variable).typeofwill just return"object". -
What is
NaNand how do you check for it? Answer:NaNstands for Not-a-Number, representing an invalid mathematical operation. Check it usingNumber.isNaN(value). Interestingly,typeof NaNreturns"number". -
Is
try/catchever mandatory in JavaScript? Answer: No. JavaScript has no checked exceptions — every error is unchecked, and nothing forces you to usetry/catch. You can throw any type (even strings), though throwingErrorobjects is best practice. -
What happens if you omit the
returnstatement in a function? Answer: The function implicitly returnsundefined. -
Write a quick script to reverse a string. Answer:
const reverseStr = str => str.split('').reverse().join('');
// 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