Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable assignment inside 'IF' condition

Tags:

javascript

php

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

like image 680
AlexMorley-Finch Avatar asked Mar 15 '12 09:03

AlexMorley-Finch


2 Answers

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 */ }
like image 145
jlb Avatar answered Oct 29 '22 13:10

jlb


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

like image 25
Anthony Grist Avatar answered Oct 29 '22 13:10

Anthony Grist