Variable assignment within an "IF" condition

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 this is a shorter way:

$my_epic_variable = my_epic_function();
if ( !$my_epic_variable ){
        die( "false" );
}

      

Could it be javascript? I had no success, wasn't sure if there was some special syntax or something

+3


source to share


4 answers


You can do the same in JavaScript with one key difference. You cannot declare a variable (locally localized) inside an if clause, you can only refer to it.

So first, declare it:

var someVar;

      

Then use it how you want:



if (!(someVar = someFunction())) { /* do some stuff */ }

      

Note that you will also have to wrap negative expressions (!(expression))

with parentheses

However, this won't work:

if (var someVar = someFunction()) { /* NOPE */ }

      

+3


source


Yes, it works great. However, if you invert ( !

) then you need to wrap the assignment in parentheses, otherwise you will get a syntax error.

function myFunc() {
    return false;
}

if(!(myVar = myFunc())) {
    console.log('true');
}    

      



Working example

+3


source


It also works in JS:

var foo = null;

if ( foo = 1 ){
 // some code
}

alert (foo);  // 1

      

Or assignment even with a function:

var foo = null;

function getFoo(){
    return 1;
}

if ( foo = getFoo() ){
 // some code
}

alert (foo); // 1

      

With negation, you need to add curly braces:

var foo = null;

function getFoo(){
    return 1;
}

if (! (foo = getFoo()) ){
 // some code
}

alert (foo); // 1

      

In the latter case, it is important to wrap the assignment operator in parentheses because it is !

used to test the result.

+2


source


This is the preferred method for me (in PHP) because it is absolutely clear that you didn't want to use a condition ==

but made a mistake.

if ( ($my_epic_variable = my_epic_function()) !== NULL ){
    // my epic function returned false
    // my epic variable is false
    die( "false" );
}

      

In JavaScript, I would probably do:

function my_epic_function() {
    return 5;
}

var my_epic_variable;
if ( (my_epic_variable = my_epic_function()) !== null ){
    alert("we're in");
}​

      

+1


source







All Articles