Get up to 80 % extra points for free! More info:

Lesson 4 - Conditions in JavaScript

In the previous lesson, Basic data types in JavaScript and its functions, we talked about data types and their functions. In today's tutoriál, we're going to look into conditions.

In order to write an interactive application, we need a way to react to the input. It could either come from the user or from the system and we'll change the program's flow according to it. This functionality is referred to as branching and is done through conditions. In JavaScript, conditions are written in the same way as in all other C-like languages (I'll explain it anyway for the beginners). The more advanced of you might get bored for a minute, however, I believe you'll find this lesson interesting at the end :)

The following code will write the text "It's after 6 PM" if i'is 6 PM or later, and it'll work until midnight. Then, the time will be set to 0 which is less than 18.

let d = new Date();
if (d.getHours() >= 18) {
    document.write("It's after 6 PM.");
}

The condition starts with the if command. We write the entire condition expression in parentheses as we're used to from Math. However, the syntax of the operators is slightly different (see the table below). If the expression is true, the first command after the condition is applied. If not, the first command is skipped and the program continues below it. If we need to run multiple commands, we have to write them into braces. Since it's more readable, braces are sometimes used even for single commands (like in the example above).

Operators

In expressions, we're able to use any of the following operators:

Operator name C-like syntax
Equal to ==
Greater than >
Less than <
Greater than or equal to >=
Less than or equal to <=
Not equal !=
Negation !

We use the == operator for equality to avoid confusing it with a normal assignment to a variable (the = operator). If we want to negate an expression, we write it in parentheses and we write an exclamation mark before the actual expression within the parentheses.

Composing conditions

Now, let's make something a bit more useful. We don't know much about processing inputs yet, so we won't skip too far ahead. We'll write a script that recognizes whether it's day or night. This could be used for things like automatized greetings (Good evening, Good day) or even for switching between the website themes (different ones for day/night).

let d = new Date();
if ((d.getHours() > 5) && (d.getHours() < 18))
    document.write("Good day");
else
    document.write("Good evening");

You might be wondering what the two ampersands (&&) do. To answer your question, please refer to the operator table for condition composition shown below:

Operator C-like syntax
And also &&
Or ||

This will do for now. Of course, we can also combine these operators using brackets. So the code above writes "Good day" if the current hour is greater than 5 AM and also less than 6 PM.

Greeting in JavaScript
localhost

We've also used another conditional command, else, which runs the following command if the condition didn't apply. This is really handy, otherwise, we'd have to write an opposite condition again for the evening.

Else is also used in case we need to change the variable used in the condition so that we can't evaluate it again afterward. The program will remember that the condition wasn't met and will run the else branch. Let's use it on an example: Consider the number a which value will be 0 or 1 and we'll want to swap between these values (if there's a 0, we'll change it to 1 and vice versa). We could naively write a code like this:

let a = 0; // stores 0 to a

if (a == 0) // if a is 0, changes it to 1
    a = 1;
if (a == 1) // if a is 1, changes it to 0
    a = 0;

document.write(a);

It doesn't work, does it? Let's see what the program does. First, we have 0 stored in a, so the first condition is met and 1 is assigned to it. However, the second condition is then met as well. How do we solve this? If we swapped the conditions, we'd end up with the same problem. That's right, we'll use else!

let a = 0; // stores 0 to a

if (a == 0) // if a is 0, changes it to 1
    a = 1;
else // if a is 1, changes it to 0
    a = 0;

document.write(a);

Let's play a little with conditions and write a script which will be able to greet visitors of your website according to the time of the day, meaning Good morning, good afternoon, .... I'm sure you'd be able to do it, we'll simply put multiple conditions consecutively and set the times respectively. Keep in mind you should use the >= and <= operators to cover all the hours properly. For those who still need a push, I'll give you a small bit of help on how to declare a sequence of conditions:

let d = new Date();
if ((d.getHours() >= 5) && (d.getHours() <= 11))
    document.write("Good morning");
else if ((d.getHours() == 12))
    document.write("Enjoy your meal");
else if ((d.getHours() >= 13) && (d.getHours() <= 17))
    document.write("Good afternoon");
else if ((d.getHours() >= 18 && (d.getHours() <= 21)))
    document.write("Good evening");
else
    document.write("Good night");

Notice that there's no if before the last else. When the program gets there, there's no other option than it's night, so we don't need any sort of verification.

Switch

If we need to react to different values of a single variable, we can use the switch construct rather than if-else sequences. Theoretically, this may sometimes seem more readable, but it's best to avoid this sort of branching and use e.g. arrays instead (more on this later on).

let value = 2;
let word;
switch (value) {
    case 1:
        word = "one";
        break;
    case 2:
        word = "two";
        break;
    case 3:
        word = "three";
        break;
    default:
        word = "undefined";
}
document.write(word);

This syntax comes from the C language and the commands in each branch are not wrapped in braces. Instead, they're separated by the break command, which is kind of unnatural and we could easily forget to add it. If none of the cases apply, the default branch is triggered, which is sort of like else. Any switch can be re-written using if-else if sequences. Aside from a different way of writing things, switches don't bring any benefits. I included them into this lesson in case you encounter them somewhere or in case you find them more readable.

Boolean

Next, we have the boolean type, which can hold only 2 values - true or false:

let haveRolls = false;
let haveBread = true;

A condition always becomes true or false in the end. Therefore, the result of a condition can be stored into a variable:

let age = 26;
let adult = (age >= 21);
document.write(adult);

If we use boolean variables in a condition, we don't have to evaluate whether the value is equal to true or not:

if (adult == true)
...

Instead, we simply evaluate the variable. The if construct expects a logical expression which has a value of either true or false:

if (adult)
...

Ternary operator

We often need to store different values according to some condition. Consider we have the user's gender stored as a boolean (male = true) and we need to convert it to a string. With our current knowledge, we'd probably come up with something like this:

let male = true; // a variable with the gender information
let genderName;
if (male)
    genderName = "male";
else
    genderName = "female";
document.write(genderName);

In order to get the value according to the result of a logical expression, we can use a ternary expression:

let male = true; // some variable with the gender information
let genderName = (male) ? "male" : "female";
document.write(genderName);

We usually put the condition in parentheses. Then, we add a question mark and the two different resulting values that we want to be returned. Values are separated by a colon. The first is returned if the condition is met and the second one if it isn't. Except for a boolean variable, we could use any other expression in the parentheses, e.g. (age >= 18) ? "adult" : "child".

Prompt()

Since you now know how to use conditions, it'd be nice to try to react to as many types of inputs as possible. Unfortunately, we're only familiar with date and time and we aren't experienced enough to read text from forms.

However, JavaScript gives us the prompt() function, which brings up a text input dialog. This function takes two input parameters. The first one is the question which is to be shown to the user and the second is the default value which will be filled into the input. You may skip the second parameter. Let's write a short application which will find out if the user is an adult:

let age = prompt("Enter your age");
document.write((age >= 21) ? "You're an adult" : "You're not an adult");

The result:

Prompt dialog in JavaScript - JavaScript Basic Constructs

Majority in JavaScript
localhost

Great! You're now able to handle conditions well and you've made a useful script to greet visitors of your website :) Also, you now know how to use the prompt() function, so you can write applications which communicate with the user. In the next lesson, Solved tasks for JavaScript lesson 4, we'll learn about loops in JavaScript.

In the following exercise, Solved tasks for JavaScript lesson 4, we're gonna practice our knowledge from previous lessons.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 9x (2.45 kB)
Application includes source codes in language JavaScript

 

Previous article
Basic data types in JavaScript and its functions
All articles in this section
JavaScript Basic Constructs
Skip article
(not recommended)
Solved tasks for JavaScript lesson 4
Article has been written for you by David Capka Hartinger
Avatar
User rating:
6 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities