Skip to content Skip to sidebar Skip to footer

Using Js Is There A Shorthand For Multiple If Else Conditions?

Is there a shorter way to have multiple if else conditions? if( suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png' && suffix != 'gif'){ console.l

Solution 1:

Using an array can be seen as a shorthand, though it does add (negligible IMHO) overhead:

if (['jpg', 'jpeg', 'png', 'gif'].indexOf(suffix) === -1) {
  console.log('not an image.');
}

Edit: even shorter with RegExp :

if (!/jpe?g|png|gif/.test(suffix)) {
  console.log('not an image.');
}

Solution 2:

Rather than an Array with indexOf, you can use an ojbect with in or hasOwnProperty:

if (suffix in {jpg:'', jpeg:'', png:'', gif:''})

or

if ({jpg:'', jpeg:'', png:'', gif:''}.hasOwnProperty(suffix))

An object approach works well if you can make use of the object for other things.

Solution 3:

Maybe not shorter but for all case statement lovers:

switch(suffix){
   case'jpg':
   case'jpeg':
   case'png':
   case'gif':
       break;
   default:
       console.log('not an image.');
       break;
}

Post a Comment for "Using Js Is There A Shorthand For Multiple If Else Conditions?"