Conditionals: Making Decisions in JavaScript

Shubhaw KumarShubhaw Kumar
6 min read

Welcome back to our JavaScript journey! In our previous post, we learned about variables, data types, and basic operations. Now it's time to make our code smarter by learning how to make decisions. This is part of the control flow. Control flow also includes loops, which we will discuss in the next post.

Control flow is what makes programs truly interactive and dynamic. Instead of just executing code line by line, we can create programs that respond to different situations and automate repetitive tasks.

Making Decisions with Conditionals

Conditionals allow your code to make decisions based on different conditions. Think of them like real-life decision-making: "If it's raining, take an umbrella. Otherwise, don't."

The syntax of the conditional statements are very similar to the real world, so it will be very easy for you to understand. Let’s take a look at them one by one:

The if Statement

The most basic conditional statement is if. It executes code only when a condition is true:

/* SYNTAX
if (condition is true) {
  then do the work
}
*/

let temperature = 28;

if (temperature > 25) {
    console.log("It's a nice day!");
}

The if...else Statement

Use else to specify what happens when the condition is false:

/* SYNTAX
if (condition is true) {
  then do the work
} else {
    do otherwise
}
*/

let age = 20;

if (age >= 18) {
    console.log("You can vote!");
} else {
    console.log("You're not old enough to vote yet.");
}

The if...else if...else Statement

For multiple conditions, chain them together:

/* SYNTAX
if (condition1 is true) {
  then do the 1st work
} else if (condition2 is true) {
  then do the 2nd work
} else {
  do something else
}
*/

let score = 85;

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

Logical Operators in Conditionals

You can combine multiple conditions using logical operators which we discussed in the last blog post:

let age = 22;
let hasLicense = true;

// AND operator (&&) - both conditions must be true
if (age >= 18 && hasLicense) {
    console.log("You can rent a car!");
}

// OR operator (||) - at least one condition must be true
let isWeekend = true;
let isHoliday = false;

if (isWeekend || isHoliday) {
    console.log("You don't have to work today!");
}

// NOT operator (!) - reverses the condition
let isLoggedIn = false;

if (!isLoggedIn) {
    console.log("Please log in to continue.");
}

The Ternary Operator (Shorthand)

For simple if...else statements, you can use the ternary operator:

let age = 20;
let status = age >= 18 ? "adult" : "minor";
console.log(status); // "adult"

// This is equivalent to:
// if (age >= 18) {
//     status = "adult";
// } else {
//     status = "minor";
// }

Switch Statements

When you have many conditions to check against a single value, switch can be cleaner than multiple if...else if statements:

let dayOfWeek = "monday";

switch (dayOfWeek) {
    case "monday":
        console.log("Start of the work week!");
        break;
    case "tuesday":
    case "wednesday":
    case "thursday":
        console.log("Midweek grind!");
        break;
    case "friday":
        console.log("TGIF!");
        break;
    case "saturday":
    case "sunday":
        console.log("Weekend vibes!");
        break;
    default:
        console.log("Invalid day");
}

Important: Don't forget the break statements! Without them, the code will "fall through" to the next case.

Real-World Example

Let's look at a practical example that shows the real world use case of conditionals:

Password Strength Checker

function checkPasswordStrength(password) {
    let strength;
    let score = 0;

    // Check length
    if (password.length >= 8) {
        score++;
    }

    // Check for uppercase letters 
    if (password !== password.toLowerCase()) {
        score++;
    }

    // Check for special characters (@, #, !)
    if (password.includes('@') || password.includes('#') || password.includes('!')) {
        score++;
    }

    // Determine strength
    if (score >= 3) {
        strength = "Strong";
    } else if (score >= 2) {
        strength = "Medium";
    } else {
        strength = "Weak";
    }

    return strength;
}

// Test the function
console.log(checkPasswordStrength("password")); // "Weak"
console.log(checkPasswordStrength("Password123")); // "Medium"
console.log(checkPasswordStrength("Password@123")); // "Strong"

Common Mistakes to Avoid

Using Assignment (=) Instead of Comparison (== or ===)

let score = 85;

// ❌ Assignment instead of comparison
if (score = 90) { // This assigns 90 to score!
    console.log("Perfect score!");
}

// ✅ Correct comparison
if (score === 90) {
    console.log("Perfect score!");
}

Not Using Strict Equality (===)

// Assume the response sent by API is { status: 200 }
let response = { status: 200 }; // note that here status is of type number

// ❌ May pass due to type coercion
if (response.status == "200") {
  // Works, but you're comparing a string to a number
}

if (response.status === "200") { 
    // ❌ Fails, unless backend sends string
}

// ✅ Safer and more predictable
if (response.status === 200) { 
    // === enforces you to always use the correct data type in your code
    // So, NO unpredictable error in future
}

Incorrect Order in else if Conditions

let score = 85;

// ❌ Incorrect order
if (score > 50) {
  // Executes because score 85 is greater than 50.
} else if (score > 80) {
  // ❌ Never reached even though it's true!
  // Because the first if block was already executed
}

// ✅ Correct order
if (score > 80) {
  // ✅ Executes
} else if (score > 50) {
  // Doesn't reach here if score is 85
}

Unintentional Fall-through in switch Statements

let fruit = 'apple';

// ❌ Incorrect (because of missing break statement)
switch (fruit) {
  case 'apple':
    console.log("It's an apple");
  case 'banana':
    console.log("It's a banana");
}
// Output:
// It's an apple
// It's a banana

// ✅ Correct
switch (fruit) {
  case 'apple':
    console.log("It's an apple");
    break; // ✅ Add break to prevent fall-through
  case 'banana':
    console.log("It's a banana");
    break;
}
// Output:
// It's an apple

Try It Yourself!

Here's a challenge to practice what you've learned:

Challenge: Create a simple grade calculator

Write a program that:

  1. Takes test scores of 5 subjects

  2. Calculates the average

  3. Determines the letter grade (A, B, C, D, F)

What's Next?

You’ve just learned how JavaScript makes choices. Now it’s time to see how to do stuff again and again without getting tired! In the next blog, we’ll dive into loops and see how you can make your code run circles (literally). Get ready for some repetition magic!

Homework: Try building a simple calculator that can add, subtract, multiply, and divide two numbers using conditionals to determine which operation to perform based on user input.


Which conditionals concept did you like the most? Share your solutions to the challenge in the comments below!

0
Subscribe to my newsletter

Read articles from Shubhaw Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shubhaw Kumar
Shubhaw Kumar

Software Engineer at Microsoft, India