Reputation: 2349
var check = someCheck();
if (check){
doOne(check);
}else{
doTwo();
}
Can I be able to write the same code without defining check var? something like this below
if (someCheck()){
doOne(<magic-value-passed-which-is-result-of_someCheck()>);
}else{
doTwo();
}
Note that check could be a true, or any object or null or undefined, what all a function call could return.
I am thinking of the following solution as
var condition;
function setCondition(stmt){
condition = stmt;
}
if ( setCondition(someCheck()) ){
doOne(condition)
}else{
doTwo();
}
still am not much happy with this one, as setCondition
is a lengthy name, wanna write simple and less code. Can we teak if
itself or similar like any idea where could we access last if
checked value? is if
a function here?
Upvotes: 0
Views: 90
Reputation: 3826
Yes, something similar is possible indeed in C-like languages (such as JavaScript):
if (check = someCheck()) { ... } // 'check' should be already defined
Upvotes: 2
Reputation: 386560
You could wrap the part in an IIFE.
ES6
(v => v ? doOne(v) : doTwo())(someCheck());
ES5
void function (v) { v ? doOne(v) : doTwo(); }(someCheck());
Upvotes: 2