NehaK
0
Q:

better way to do nested if statements javascipt

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 
  
var i = 20; 
  
if (i == 10) 
  document.write("i is 10"); 
else if (i == 15) 
  document.write("i is 15"); 
else if (i == 20) 
  document.write("i is 20"); 
else
  document.write("i is not present"); 
< /script> 
2
/_ 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');
  }
}
0

New to Communities?

Join the community