简体   繁体   中英

variable assignment inside '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 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

It works in JS too:

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 braces:

var foo = null;

function getFoo(){
    return 1;
}

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

alert (foo); // 1

In the last case, it is important to wrap assignment statement in parenthesis because ! is then used to check against the result of that.

This is the preferred method for me (in PHP), because it makes it absolutely clear that you didn't mean to use the == 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'd probably do:

function my_epic_function() {
    return 5;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM