in php, something like this is fine:
<?php
if ( !$my_epic_variable = my_epic_function() ){
// my epic function returned false
// my epic variable is false
die( "false" );
}
echo $my_epic_variable;
?>
I suppose is a shorter way of doing:
$my_epic_variable = my_epic_function();
if ( !$my_epic_variable ){
die( "false" );
}
Can this be done is javascript? I've tried to no success, wasnt sure if there was some kind of special syntax or something
You can do the same in JavaScript, with one key difference. You cannot declare a (locally scoped) variable inside the if clause, you may only refer to it.
So, declare it first:
var someVar;
Then use it however you want:
if (!(someVar = someFunction())) { /* do some stuff */ }
Notice that you will also have to wrap negated expressions (!(expression))
with parentheses
This however, will not work:
if (var someVar = someFunction()) { /* NOPE */ }
Yes, that works fine. However, if you're inversing (!
), then you need to wrap the assignment in parentheses otherwise you'll get a syntax error.
function myFunc() {
return false;
}
if(!(myVar = myFunc())) {
console.log('true');
}
Working example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With