Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the conditions value in if/else

Tags:

javascript

I'm wondering if it's possible to access a condition's value directly like the following example.

var a = ["pear", "kiwi", "orange", "apple"]
if(a.indexOf("orange") !== -1){
  console.log(this) //as a.indexOf("orange") has been evaluated already above this prints 2
}

This would also make ternary operators less bloaty

var a = ["pear", "kiwi", "orange", "apple"]
var b = ((a.indexOf("orange") !== -1) ? this : '') //"this" equals 2

Thanks

EDIT: Clearing this question up for any future visitors. Basically this question is about retrieving the resulting value of what is evaluated in an if/else statement. In the example of

var a = ["pear", "kiwi", "orange", "apple"]
if(a.indexOf("orange") !== -1){ //is basically if(2 !== -1)
  console.log(this) //would then be "2" from the already evaluted a.indexOf from above
}
like image 529
Charles Avatar asked Dec 30 '16 18:12

Charles


1 Answers

You can simply store it before the statement if the goal is to not evaluate twice. The answer to your literal question is no.

const orangeIndex = a.indexOf("orange")

if (orangeIndex !== -1) {
  console.log(orangeIndex)
}

Same concept applies to the ternary operator.

As others have shown, you can also declare a variable and do the actual assignment in the if statement itself, but IMO this makes your code less readable without adding any value.

like image 112
aw04 Avatar answered Oct 07 '22 05:10

aw04