nested or if javascript code example

Example 1: nested if javascript

if(a == 'value'){
    doSomething();
    if(b == 'another value'){
        doAnotherThing();
    }
}

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