JavaScript Control Flow Conditionals

Ternary

What if we want to bind the result of an if statement directly to a variable or a constant? The normal if statement won't allow us to do that, but the ternary operator will.

The ternary operator is often a fast way of writing an if statement combined with an else statement that works as an expression, meaning we can bind the result. The syntax is quite straight forward as shown below.

const x = condition ? valueIfTruthy : valueIfFalsy

The ternary operator is the only operator in JavaScript that requires three operands:

  1. A condition.
  2. An expression if the condition is truthy.
  3. An expression if the condition is false.

If the condition is true, then the expression after the question mark will be executed, otherwise the expression after the colon will be executed. The truthy and falsy expressions are mandatory, which means that we must specify both expressions.

Equivalent

A ternary operator can be de-sugared to a combination of an if statement and an else statement as shown below.

let x;
if (condition) {
x = valueIfTruthy
} else {
x = valueIfFalsy
}

is equivalent to

const x = condition ? valueIfTruthy : valueIfFalsy

Read more on MDN

Conditional (ternary) operator

Test yourself

Description

Define a new function with the name

translateSentence

that takes an English string input parameter sentence and returns a best effort translated sentence in Norwegian.

We have defined a function translateWord that translates some English words to Norwegian for you. This function returns the translated word if it is able to translate it, and returns "ERROR" if not.

Replace the words in the sentence that could be translated to Norwegian and leave the rest as they are in the original English sentence.

Assumptions:

  • The translateWord function is provided and available for use.

Tips:

  • Split the sentence into words using split.
  • Use map to transform the list of English words to Norwegian.
  • Join the array back to a string using join.

Tests

  1. 1 You should define a function named translateSentence.
  2. 2translateSentence("the oak fought the wind and was broken, the willow bent when it must and survived.") should return "the eik fought the vind and was broken, the seljetre bent when it must and survived.".
  3. 3translateSentence("life is a dream from which we all must wake before we can dream again.") should return "livet is a drøm from which we all must våkne before we can drøm again.".
  4. 4translateSentence("at my age, if i make it up, it's still an old saying.") should return "at my age, if i make it up, it's still an gammelt saying.".
Editor