CoursePart 1 — JavaScript for PlaywrightLesson 1.8
Lesson 1.8Part 1 — JavaScript for Playwright

if / else and ternary

Making decisions in code — if/else and the shortcut ? : form.

Lesson 1.8of 24
Next

Step 1

The idea

01

Every decision in code is an if/else. Literally every one.

"If the button is visible, click it. Otherwise, log an error." That's an if/else. "If the user is logged in, show the dashboard. Otherwise, redirect to login." Same structure.

The syntax in JavaScript mirrors how you think in English — once you see it, you can't unsee it.

Step 2

See it run

02
Output
Score: 82
Grade: B
Result: PASS
Quick result: PASS
if-else.js
const score = 82;

// Basic if/else
if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 80) {
  console.log("Grade: B");
} else if (score >= 70) {
  console.log("Grade: C");
} else {
  console.log("Grade: F");
}

// You can also store the result in a variable
let result;
if (score >= 60) {
  result = "PASS";
} else {
  result = "FAIL";
}
console.log("Result:", result);

// Ternary — a one-line shortcut for simple if/else
const quickResult = score >= 60 ? "PASS" : "FAIL";
console.log("Quick result:", quickResult);
Terminal
$ node if-else.js

The ternary reads as: condition ? value-if-true : value-if-false

Step 3

Now you try

03

Change score to 55 and predict the output before running. Then try 92.

Bonus: write a ternary that checks if a username has more than 3 characters and returns "valid" or "too short":

js
const username = "QA";
// write your ternary here
💡Tip
Ternaries are great for one-liner decisions. For anything with more than 2 branches, use full if/else — it's easier to read.

Step 4

Why a tester cares

04

if/else decisions appear in every real program. Here's a simple shipping cost calculator — the kind of logic that's inside every e-commerce site:

shipping.js
function getShippingCost(orderTotal, isMember) {
  if (isMember && orderTotal >= 500) {
    return 0;                  // free shipping for members with big orders
  } else if (isMember) {
    return 49;                 // discounted shipping for members
  } else if (orderTotal >= 1000) {
    return 0;                  // free shipping for large non-member orders
  } else {
    return 99;                 // standard shipping
  }
}

console.log(getShippingCost(600, true));   // 0
console.log(getShippingCost(200, true));   // 49
console.log(getShippingCost(1200, false)); // 0
console.log(getShippingCost(300, false));  // 99
Terminal
$ node shipping.js

Notice how each if / else if / else branch handles one specific case. That clear structure is what makes code readable and maintainable.

Recap

3 key points
  • 1if/else runs different code depending on whether a condition is true or false.
  • 2else if lets you chain multiple conditions — JS picks the first matching branch.
  • 3Ternary (condition ? a : b) is a one-line shortcut — use it for simple true/false swaps.