Home > Back-end >  js if else result as condition in another if
js if else result as condition in another if

Time:02-24

I'm wondering if it is possible to use in javascript the result of one if/else statement as condition for another if/else statement. Let me visualize this idea with the code:

if ( if (thatstrue) { return true } else { return false } ) {
 do something
 }

CodePudding user response:

Yes! You can use ternary operator if statement as condition that way:

a = true;

ifFunction = function() {
  if ( true && a ? true : false) {
  console.log('a is true');
  } else {
  console.log('a is false');
  }
}

ifFunction();

a= false;

ifFunction();

I'm giving this Q&A style post becouse i had this problem today in a much more complicated situation with connection with other conditions and couldn't search for a simple and direct answer anywhere. I found a solution by myself hardly reminding myself one line ternary operator and trying to use it. I found it working! Begginners in js mostly use classic if/else conditional blocks (which You can't use that way) and are not familiar with the ternary if/else statement way, which You can simply use as condition in other if else statement. I hope i will help some noob coders like me ;) If i did than please vote me up :D

CodePudding user response:

I think the best way to always do this is to abstract the first condition to a function. You can even use it to take parameters and add additional logic iif you need to expand the use case.

var a = 'foobar'

function checkForSomeACondition() {
  return a === myTrueCondition
}


// ...then 

if (checkForSomeACondition()){
  // do something
} else {
  // do something else
}

  • Related