Conditional operators: if, '?'

Sometimes we need to perform different actions basing on a condition.

There’s an if operator for that and also the “question mark” operator: "?" for conditional evaluation.

The “if” operator

The “if” operator gets a condition, evaluates it and – if the result is true – executes the code.

For example:

let year = prompt('In which year was ECMAScript-2015 specification published?', '');

if (year == 2015) alert( 'You are right!' );

In the example above, the condition is a simple equality check: year == 2015, but it can be much more complex.

If there’s more than one command to execute – we can use a code block in figure brackets:

if (year == 2015) {
  alert( "That's correct!" );
  alert( "You're so smart!" );
}

It is recommended to use figure brackets every time with if, even if there’s only one command. That improves readability.

Boolean conversion

The if (…) operator evaluates the expression in parentheses and converts it to the boolean type.

Let’s recall the conversion rules:

  • A number 0, an empty string "", null, undefined and NaN are false,
  • Other values – true.

So, the code under this condition would never execute:

if (0) { // 0 is falsy
  ...
}

…And inside this condition – always works:

if (1) { // 1 is truthy
  ...
}

We can also pass a pre-evaluated boolean value to if, like here:

let cond = (year == 2015); // equality evaluates to true or false

if (cond) {
  ...
}

The “else” clause

The if operator may contain an optional “else” block. It executes when the condition is wrong.

For example:

let year = prompt('In which year was ECMAScript-2015 specification published?', '');

if (year == 2015) {
  alert( 'You guessed it right!' );
} else {
  alert( 'How can you be so wrong?' ); // any value except 2015
}

Several conditions: “else if”

Sometimes we’d like to test several variants of a condition. There’s an else if clause for that.

For example:

let year = prompt('In which year was ECMAScript-2015 specification published?', '');

if (year < 2015) {
  alert( 'Too early...' );
} else if (year > 2015) {
  alert( 'Too late' );
} else {
  alert( 'Exactly!' );
}

In the code above JavaScript first checks year < 2015, if it is falsy then goes to the next condition year > 2015, and otherwise shows the last alert.

There can be more else if blocks. The ending else is optional.

Ternary operator ‘?’

Sometimes we need to assign a variable depending on a condition.

For instance:

let accessAllowed;
let age = prompt('How old are you?', '');

if (age > 18) {
  accessAllowed = true;
} else {
  accessAllowed = false;
}

alert(accessAllowed);

The so-called “ternary” or “question mark” operator allows to do that shorter and simpler.

The operator is represented by a question mark "?". The formal term “ternary” means that the operator has 3 operands. It is actually the one and only operator in JavaScript which has that many.

The syntax is:

let result = condition ? value1 : value2

The condition is evaluated, if it’s truthy then value1 is returned, otherwise – value2.

For example:

let accessAllowed = (age > 18) ? true : false;

Technically, we can omit parentheses around age > 14. The question mark operator has a low precedence. It executes after the comparison >, so that’ll do the same:

// the comparison operator "age > 18" executes first anyway
// (no need to wrap it into parentheses)
let accessAllowed = age > 18 ? true : false;

…But parentheses make the code more readable. So it’s recommended to put them.

Please note:

In the example above it’s possible to evade the question mark operator, because the comparison by itself returns true/false:

// the same
let accessAllowed = age > 18;

Multiple ‘?’

A sequence of question mark "?" operators allows to return a value depending on more than one condition.

For instance:

let age = prompt('age?', 18);

let message = (age < 3) ? 'Hi, baby!' :
  (age < 18) ? 'Hello!' :
  (age < 100) ? 'Greetings!' :
  'What an unusual age!';

alert( message );

It may be difficult at first to grasp what’s going on. But after a closer look we can see that it’s just an ordinary sequence of tests.

  1. The first question mark checks whether age < 3.
  2. If true – returns 'Hi, baby!', otherwise – goes after the colon ":" and checks for age < 18.
  3. If that’s true – returns 'Hello!', otherwise – goes after the next colon ":" and checks for age < 100.
  4. If that’s true – returns 'Greetings!', otherwise – goes after the last colon ":" and returns 'What an unusual age!'.

The same logic using if..else:

if (age < 3) {
  message = 'Hi, baby!';
} else if (a < 18) {
  message = 'Hello!';
} else if (age < 100) {
  message = 'Greetings!';
} else {
  message = 'What an unusual age!';
}

Non-traditional use of ‘?’

Sometimes the question mark '?' is used as a replacement for if:

let company = prompt('Which company created JavaScript?', '');

(company == 'Netscape') ?
   alert('Right!') : alert('Wrong.');

Depending on the condition company == 'Netscape', either the first or the second part after "?" gets executed and shows the alert.

We don’t assign a result to a variable here, the idea is to execute different code depending on the condition.

It is not recommended to use the question mark operator in this way.

The notation seem to be shorter than if, that appeals to some programmers. But it is less readable.

Here’s the same with if for comparison:

let company = prompt('Which company created JavaScript?', '');

if (company == 'Netscape') {
  alert('Right!');
} else {
  alert('Wrong.');
}

Our eyes scan the code vertically. The constructs which span several lines are easier to understand than a long horizontal instruction set.

The idea of a question mark '?' is to return one or another value depending on the condition. Please use it for exactly that. There’s if to execute different branches of the code.

Tasks

importance: 5

Will alert be shown?

if ("0") {
  alert( 'Hello' );
}

Yes, it will.

Any string except an empty one (and "0" is not empty) becomes true in the logical context.

We can run and check:

if ("0") {
  alert( 'Hello' );
}
importance: 2

Using the if..else construct, write the code which asks: ‘What is the “official” name of JavaScript?’

If the visitor enters “ECMAScript”, then output “Right!”, otherwise – output: “Didn’t know? ECMAScript!”

Demo in new window

<!DOCTYPE html>
<html>

<body>
  <script>
    'use strict';

    let value = prompt('What is the "official" name of JavaScript?', '');

    if (value == 'ECMAScript') {
      alert('Right!');
    } else {
      alert("You don't know? ECMAScript!");
    }
  </script>


</body>

</html>
importance: 2

Using if..else, write the code which gets a number via prompt and then shows in alert:

  • 1, if the value is greater than zero,
  • -1, if less than zero,
  • 0, if equals zero.

In this task we assume that the input is always a number.

Demo in new window

let value = prompt('Type a number', 0);

if (value > 0) {
  alert( 1 );
} else if (value < 0) {
  alert( -1 );
} else {
  alert( 0 );
}
importance: 3

Write the code which asks for a login with prompt.

If the visitor enters "Admin", then prompt for a password, if the input is an empty line or Esc – show “Canceled.”, if it’s another string – then show “I don’t know you”.

The password is checked as follows:

  • If it equals “TheMaster”, then show “Welcome!”,
  • Another string – show “Wrong password”,
  • For an empty string or cancelled input, show “Canceled.”

The schema:

Please use nested if blocks. Mind the overall readability of the code.

Run the demo

let userName = prompt("Who's there?", '');

if (userName == 'Admin') {

  let pass = prompt('Password?', '');

  if (pass == 'TheMaster') {
    alert( 'Welcome!' );
  } else if (pass == null || pass == '') { // (*)
    alert( 'Canceled.' );
  } else {
    alert( 'Wrong password' );
  }

} else if (userName == null || userName == '') { // (**)

  alert( 'Canceled' );

} else {

  alert( "I don't know you" );

}

Please note the if check in lines (*) and (**). Every browser except Safari returns null when the input is canceled, and Safari returns an empty string. So we must treat them same for compatibility.

Also note the vertical indents inside the if blocks. They are technically not required, but make the code more readable.

importance: 5

Rewrite this if using the ternary operator '?':

if (a + b < 4) {
  result = 'Below';
} else {
  result = 'Over';
}
result = (a + b < 4) ? 'Below' : 'Over';
importance: 5

Rewrite if..else using multiple ternary operators '?'.

For readability, it’s recommended to split the code into multiple lines.

let message;

if (login == 'Employee') {
  message = 'Hello';
} else if (login == 'Director') {
  message = 'Greetings';
} else if (login == '') {
  message = 'No login';
} else {
  message = '';
}
let message = (login == 'Employee') ? 'Hello' :
  (login == 'Director') ? 'Greetings' :
  (login == '') ? 'No login' :
  '';
Tutorial map

Comments

read this before commenting…
  • You're welcome to post additions, questions to the articles and answers to them.
  • To insert a few words of code, use the <code> tag, for several lines – use <pre>, for more than 10 lines – use a sandbox (plnkr, JSBin, codepen…)
  • If you can't understand something in the article – please elaborate.