The if(...) statement evaluates a condition in parentheses and, if the result is true, executes a block of code. Example:

let year = 2015;

if (year === 2015) console.log( 'You are right!' );

The if(...) statement evaluates a condition in parentheses and, if the result is true, executes a block of code.

If we want to execute more than one statement, we have to wrap our code block inside curly braces:

if (year == 2015) {
  console.log( 'You are right!' );
  alert( "You're so smart!" );
}

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 “conditional” or “question mark/ternary operator” operator lets us do that in a shorter and simpler way.

The operator is represented by a question mark ?. Sometimes it’s called “ternary”, because the operator has three 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 the parentheses around age > 18. The question mark operator executes after the comparison >. This example will do the same thing as the previous one:

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