Conditionals in JavaScript

Conditionals are yet another fundamental part of programming. They help your code make decisions and perform different actions based on specific conditions.

In this section, we'll start adding logic to your applications so you can make decisions based on different conditions.

if

The if statement is like a question your code asks: "Is this condition true?" If the answer is yes, it runs a block of code.

Here's an example:

let score = 85;

if (score >= 75) {
  console.log("You passed the test!");
}

In this example, the code checks whether the score is 75 or higher. If it is, it prints "You passed the test!" to the console.

else

What if the answer to our if question is no? That's where the else statement comes in.

It provides an alternate block of code to run when the if condition is false. Think about it as a fallback if our condition isn't hit.

let score = 65;

if (score >= 75) {
  console.log("You passed the test!");
} else {
  console.log("You didn't pass the test.");
}

If the score is 75 or higher, it prints "You passed the test!". Otherwise, it prints "You didn't pass the test."

else if

Sometimes, we need to check more than one condition. That's where else if comes in handy. It lets you add more checks between if and else:

const score = 65;

if (score >= 90) {
  console.log("Excellent!");
} else if (score >= 75) {
  console.log("Good job!");
} else if (score >= 50) {
  console.log("You passed!");
} else {
  console.log("Better luck next time.");
}

In this example:

  • If score is 90 or above, it prints "Excellent!"
  • If score is between 75 and 89, it prints "Good job!"
  • If score is between 50 and 74, it prints "You passed!"
  • If none of these conditions are met, it prints "Better luck next time."

Logical Operators Reminder

It's been a while since we looked at operators in JavaScript.

But as a reminder, logical operators help combine multiple conditions. The most common ones are:

  • && (AND): All conditions must be true.
  • || (OR): At least one condition must be true.
  • ! (NOT): Flips the condition from true to false, or vice versa.

And a example:

const hasTicket = true;
const isVIP = false;

if (hasTicket || isVIP) {
  console.log("Welcome to the event!");
} else {
  console.log("You need a ticket to enter.");
}

In this example, the message "Welcome to the event!" will be printed if the person has a ticket or is a VIP.

Using Functions with Conditionals

Let's create a function that checks if a person qualifies for a discount based on age or membership status:

function isEligibleForDiscount(age, isMember) {
  if (age < 18 || age >= 65 || isMember) {
    return "Eligible for discount";
  } else {
    return "Not eligible for discount";
  }
}

console.log(isEligibleForDiscount(17, false)); // Outputs: Eligible for discount
console.log(isEligibleForDiscount(30, true));  // Outputs: Eligible for discount
console.log(isEligibleForDiscount(30, false)); // Outputs: Not eligible for discount

In this example, the isEligibleForDiscount function checks whether a person under 18, 65 or older, or a member is eligible for a discount.

Ternary Operator

The ternary operator is a shortcut for writing simple if-else statements, which is great for making quick decisions.

It works like this:

condition ? valueIfTrue : valueIfFalse;

It might make more sense on how or why you would use it with a practical example:

const isLoggedIn = true;
const message = isLoggedIn ? "Welcome back!" : "Please log in.";
console.log(message); // Outputs: Welcome back!

In this example, the ternary operator checks if isLoggedIn is true. If true, it assigns "Welcome back!" to the message variable; otherwise, it assigns "Please log in."

Understanding Truthy and Falsy Values

In JavaScript, some values are treated as true or false in a Boolean context. These are known as "truthy" and "falsy" values.

Falsy values include:

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN (Not a Number)

Truthy values are pretty much everything else, including:

  • Non-zero numbers (e.g., 1, -1, 3.14)
  • Non-empty strings (e.g., "hello", "0")
  • Arrays (even empty arrays) (e.g., [])
  • Objects (even empty objects) (e.g., {})
  • Functions

As usual, let's look at an example that you can play around with:

const value = "hello";

if (value) {
  console.log("This is truthy");
} else {
  console.log("This is falsy");
}

In this example, the string "hello" is truthy, so the console will output "This is truthy".

Practice: Using Conditionals

  1. Test Scores: Write a program that evaluates a test score and logs a message indicating the performance level (e.g., Excellent, Good job, Passed, Better luck next time).
const score = 85;

if (score >= 90) {
  console.log("Excellent!");
} else if (score >= 75) {
  console.log("Good job!");
} else if (score >= 50) {
  console.log("You passed!");
} else {
  console.log("Better luck next time.");
}
  1. Discount Eligibility: Create a function isEligibleForDiscount that takes age and membership status and checks if a person is eligible for a discount.
function isEligibleForDiscount(age, isMember) {
  if (age < 18 || age >= 65 || isMember) {
    return "Eligible for discount";
  } else {
    return "Not eligible for discount";
  }
}

console.log(isEligibleForDiscount(17, false)); // Outputs: Eligible for discount
console.log(isEligibleForDiscount(30, true));  // Outputs: Eligible for discount
console.log(isEligibleForDiscount(30, false)); // Outputs: Not eligible for discount
  1. User Greeting: Use the ternary operator to check if a user is logged in and display the appropriate message.
const isLoggedIn = false;
const message = isLoggedIn ? "Welcome back!" : "Please log in.";
console.log(message); // Outputs: Please log in.

Remember, conditionals are like the decision-makers of your code.

Conditionals let your programs react differently based on the situation, making them more dynamic and interactive. Whether checking if a user is logged in, determining if a test score passes, or deciding if someone gets a discount, conditionals help you steer your code in the right direction.

Understanding how to use if, else, else if, and even the ternary operator, plus knowing about truthy and falsy values, gives you the tools to build smarter and more responsive applications.

So, keep practicing these concepts, and you'll be ready to handle all sorts of decisions in your coding journey!

In the next section, we will look at creating loops, another concept that will take your apps to the next level.

JavaScriptBeginner
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.