Equivalent to PHP `if ($ variable = 5) {}`

I don’t know if this has a term for itself or not, but in PHP I can do:

if ($variable = 5) { echo $variable; // 5 } 

Where the same for JS fails:

 if (var variable = 5) { echo variable; // Unexpected token var } 

Is there an equivalent?

+4
source share
3 answers

You cannot define a variable inside an if block. So the answer is no, you cannot do this in javascript. In PHP, a variable definition will return true , which will control if .

But the assignment operator returns true, so you can use:

 var $variable; if($variable = 5) { alert($variable); } 
+4
source

var variable should be at the beginning of the function block, and not inside the expression.

 var variable; if( variable = 5) { alert(variable); } 

Of course, he is completely redundant ...

+2
source

You can declare a variable before the if clause:

 var variable; if (variable = 5) { console.log( variable ); // logs 5 } 
+1
source

All Articles