Categories
JavaScript

Conditional statements in JavaScript

One of the most incredible powers you can give to your JavaScript program is the ability to make decisions on its own.

Whether you want your program to decide the best time to ask a visitor to subscribe to your newsletter or display your site content in a different language, conditional statements will allow your JavaScript program to make decisions based on conditions and then act on them.

In a way, conditional statements give intelligence to your programs. And this adds a powerful layer of sophistication to any JavaScript program.

This guide will help you understand conditional statements in the JavaScript language. Specifically, it will help you understand conditional statement syntax and how to write and use conditional statements.

What is a JavaScript conditional statement?

A conditional statement tells JavaScript how it should behave when a certain condition is met.

For example, if a user visits your website and their preferred language is French, you could use a JavaScript conditional statement to determine the user’s preferred language is French, and then display the content of your website in French to them.

The best part? You aren’t limited to a single condition, you can repeat this approach for any number of conditions — if the user prefers German, display the page in German, if they prefer Russian, display it in Russian.

An interesting thing about conditional statements is how simple they are. A conditional statement really has only two parts:

  1. the condition
  2. the action to perform once the condition is met

In the language examples above, the condition would be the user’s language preference, and the action to perform would be to display the content in the preferred language.

Another way to think of a conditional statement is to compare it to how you’d make a decision about what time you’ll wake up.

Let’s imagine you had a job that required you to arrive at work by 9 a.m. from Monday to Friday.

Let’s also imagine that you needed to wake up two hours before 9 a.m to arrive to work on time.

The conditions in this example would be pretty simple:

If it’s Monday, Tuesday, Wednesday, Thursday or Friday, you’ll need to wake up at 7 a.m., otherwise, you can wake up any time you’d like.

Let’s take a look at JavaScript conditional statement structure and syntax to get a better grip on how it works.

JavaScript conditional statement structure and syntax

Conditional statements in JavaScript rely on a set of three basic syntax keywords: if, else and else if.

Here’s what this looks like:

if (condition === true) {
  //execute this code
}
else if (alternative condition === true) {
  //execute this code
}
else {
  //execute this code
}

Let’s break down what’s actually going on here:

  1. You specify a condition to match within the opening ( and closing ) with the keyword if.
  2. JavaScript checks if the condition is matched.
  3. If the condition is matched, JavaScript identifies the condition as true.
    • JavaScript then executes the code within the opening { and closing } associated with the condition which is true.
  4. If the condition is not matched, JavaScript identifies the condition as false.
    • JavaScript skips the code associated with the condition which returned false and proceeds to check if the condition within the next else if statement is true.
      • If the condition is matched, JavaScript identifies the condition as true and executes the code within the associated opening { and closing }.
      • If the condition is not matched, JavaScript identifies the condition as false.

The process above is repeated until each condition is checked.

If none of the conditions return true then the final else statement will run.

Once a condition is matched as true the conditional statement stops running. Only if the condition is false will JavaScript proceed to the next condition.

Let’s dissect the syntax.

The if keyword tells JavaScript which condition it should listen for.

The content within the opening ( and closing ) is the specific condition that must be matched. They will return as either true if matched and false if not matched.

The code between the opening { and closing } will run if the preceding condition is true.

The else if keyword tells JavaScript what to do when the previous condition is false, and the associated opening { and closing } is the code JavaScript will then execute.

The else keyword tells JavaScript what to do when none of the previous conditions are true. The code within the associated opening { and closing } is the code JavaScript will then execute.

Let’s take a look at another example using our alarm clock where the if condition is Monday, Tuesday, Wednesday, Thursday or Friday.

Here’s what this looks like:

if (Monday, Tuesday, Wednesday, Thursay or Friday === true) {
  //execute this code
  console.log("Time to wake up!");
}
else {
  //execute this code
  console.log("It's ok, you can sleep in");
}

To reiterate, when it is Monday, Tuesday, Wednesday, Thursday or Friday, the if condition will return as true.

When the if condition is true JavaScript will execute the code within the associated opening { and closing }. In the code example above, this is console.log("Time to wake up!");

Otherwise, if the condition is false, and it is not Monday, Tuesday, Wednesday, Thursday or Friday, JavaScript will skip the associated code within the opening { and closing } and instead execute the code within the opening { and closing } which follows the else keyword.

Additionally, as mentioned, you are not limited to two conditions, you can add as many conditions as you’d like with else if.

Here’s what this looks like:

if (Monday === true) {
  //execute this code
  console.log("It's Monday, time to wake up!");
}
else if (Tuesday === true) {
  //execute this code
  console.log("It's Tuesday, time to wake up!");
}
else if (Wednesday === true) {
  //execute this code
  console.log("It's Wednesday, time to wake up!");
}
else if (Thursday === true){
  //execute this code
  console.log("It's Thursday, time to wake up!");
}
else if (Friday === true){
  //execute this code
  console.log("It's Friday, time to wake up!");
}
else {
  //execute this code
  console.log("It's ok, you can sleep in");
}

Clear as mud?

Don’t worry, let’s practice by building a working alarm clock, it’s the perfect way to get a real understanding of conditional statements.

Writing a program with JavaScript conditional statements

Let’s start by creating a few variables in your JavaScript developer console to get the current day of the week.

var currentDate = new Date();
var dayOfWeek = currentDate.getDay();

The variable currentDate uses the new Date() constructor to tell your web browser what date it is.

The variable dayOfWeek then applies the getDay() method to currentDate and returns an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, 3 for Wednesday, 4 for Thursday, 5 for Friday and 6 for Saturday.

Let’s add a conditional statement to alert us if it’s a day of the week.

var currentDate = new Date();
var dayOfWeek = currentDate.getDay();

if (dayOfWeek === 0 || 1 || 2 || 3 || 4 || 5 || 6 ) {
  alert("It's a weekday, make sure you are awake by 7 a.m.");
}

Notice the use of ||, called an OR logical operator, within the opening ( and closing )?

This tells JavaScript that it can match 0 or 1 or 2 or 3 or 4 or 5 or 6.

They are really useful and allow you to specify multiple conditions for a single set of actions. In the example above, it allows us to specify each day of the week.

Ok, now let’s add an else keyword to our code to tell JavaScript what to do when it’s a weekend and the conditions above are not met.

var currentDate = new Date();
var dayOfWeek = currentDate.getDay();

if (dayOfWeek === 0 || 1 || 2 || 3 || 4 || 5 || 6 ) {
  alert("It's a weekday, make sure you are awake by 7 a.m.");
}
else {
alert("Relax, you can sleep in, it's the weekend!");
}

Now, let’s make this a bit more robust, let’s add an additional condition for Wednesday, when you work from home, with the use of else if keyword.

We’ll need to remove Wednesday from our first if condition and then add it to a newly created else if condition.

var currentDate = new Date();
var dayOfWeek = currentDate.getDay();

if (dayOfWeek === 0 || 1 || 2 || 4 || 5 || 6 ) {
  alert("It's a weekday, make sure you are awake by 7 a.m.");
}
else if (dayOfWeek === 3) {
alert("You work from home today, you can wake up a bit later at 8 a.m.");
}
else {
alert("Relax, you can sleep in, it's the weekend!");
}

And voila, you now have a working alarm clock in your JavaScript console that knows the difference between weekdays, weekends, and when you work from home.

Pretty neat right?

Hopefully, now you understand why conditional statements give intelligence to your programs. And how this adds a powerful layer of sophistication to your JavaScript program.

Next up, let’s take a look at JavaScript objects, the most powerful concept in JavaScript programming.