Home > Enterprise >  Simply if else condition in JavaScript/es6
Simply if else condition in JavaScript/es6

Time:01-08

How do I make this if else more simple.

if (!request) {
  return 'no request';
} else {
  if (loading === '404') {
    return 'rejected';
  }
  if (loading === '200' && !array1.length) {
    return 'fulfilled';
  }
}

if any ternary operator then how can I make it

CodePudding user response:

You could omit else part, because you return if true.

if (!request) return 'no request';
if (loading === '404') return 'rejected';
if (loading === '200' && !array1.length) return 'fulfilled';

CodePudding user response:

You can use if-elseif-else statement

if(!request) return 'no request'
else if(loading === '404') return 'rejected'
else if(loading === '200' && !array.length) return 'fulfilled'

CodePudding user response:

one might consider ...

{
  // ...
  return ((!request && 'no request')
    || (loading === '404' && 'rejected')
    || (loading === '200' && !array1.length && 'fulfilled')
    || undefined // or 'failure' // or 'not fulfilled'
  );
}

... or ...

{
  // ...
  let returnValue = (!request && 'no request')
    || (loading === '404' && 'rejected')
    || (loading === '200' && !array1.length && 'fulfilled')
    || undefined; // or 'failure'; // or 'not fulfilled';
  
  // do more stuff ...
  // ...
  // ... maybe even change `returnValue` again.
  
  return returnValue;      
}

CodePudding user response:

if (request) {
  switch (loading) {
    case "404":
      return "rejected";
    case "200":
      if (!array1.length) return "filfilled";
      break;
  }
} else {
  return "no request";
}

I think a switch statement is better here considering that you may get more cases.

CodePudding user response:

You can also simply do this with the ternary operator. Hope the below code will you.

!request ? 'no request' : loading === '404' ? 'rejected' : 'fullfilled'
  •  Tags:  
  • Related