The if Statements

Decisions are made in JavaScript with if statements. Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

Syntax

if (condition1) {
    do this;
} else if (condition2) {           
    do that;
} else {
    do something else;
}

The simplest if statement

let n = 3;

if (n > 1) {
    console.log(n);
}

The console result:

3

Adding an else

else statement is optional. But if you include the else, you have to put a block of code under it.

let n = 3;

if (n > 10) {
    console.log(n + ' is larger than 10');
} else {
    console.log(n + ' is smaller than 10');
}

Console result:

3 is smaller than 10

Then change n = 3 to be n = 12, run again:

12 is larger than 10

Testing many things with else if

You can test multiple conditions with if/else if statement.

If you want to test other conditions after the first if statement, add more else if statements after it. You may have as many else if statements as you'd like, but note that after the computer finds a condition that is true and runs the code inside, it will skip over all of the remaining statements so that it only runs one in the entire set of if/else if/else statements.

let age = prompt('Enter your age: ');

if (age > 12) {
    console.log('It will be hard to get you laugh.');
} else if (age > 5) {
    console.log('What did O say to 8?');
    console.log('Nice belt!');
} else {
    console.log('You are too young for my jokes.');
}

Run the program, the pop up window shows a message:

Enter your age:

Type in 8 Console shows results:

What did O said to 8?
Nice belt!

Next run again and enter 15:

Enter your age: 15
It will be hard to get you laugh.

Example EvenOdd()

In the function, enter a number, based on it's even or odd to print out a message.

function EvenOdd() {
  let n = prompt('Enter an integer here: ');
  if (n % 2 == 0) {
    console.log("The number is even."); 
  } else {
    console.log("The number is odd."); 
  } 
}     

// call the function  
EvenOdd()

Run the program a few times, each time enter a different number, you will get message like this:

Enter an integer here: 8
The number is even.

Enter an integer here: 15
The number is odd.

results matching ""

    No results matching ""