nested if statements code example

Example 1: multiple if condition in excel

IF( condition1, value_if_true1, IF( condition2, value_if_true2, value_if_false2 ))

Example 2: better way to do nested if statements javascipt

/_ return early when invalid conditions found _/

function test(fruit, quantity) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

  if (!fruit) throw new Error('No fruit!'); // condition 1: throw error early
  if (!redFruits.includes(fruit)) return; // condition 2: stop when fruit is not red

  console.log('red');

  // condition 3: must be big quantity
  if (quantity > 10) {
    console.log('big quantity');
  }
}

Tags:

Misc Example