4

I do not know whether 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?

tomsseisums
  • 13,168
  • 19
  • 83
  • 145
  • 2
    Seems to work with `var variable; if (variable = 5) ...`. – Seth Carnegie Jan 09 '13 at 16:11
  • No, declaration requires a `var` *statement*, and there is not an expression equivalent. – pimvdb Jan 09 '13 at 16:11
  • What's the goal ? The PHP code you show looks just like something that should not be allowed in order to have maintainable code. – Denys Séguret Jan 09 '13 at 16:12
  • 1
    This is called putting an assignment inside a conditional, and it is a bad practice. [Related question](http://stackoverflow.com/questions/2576571/javascript-assign-variable-in-if-condition-statement-good-practice-or-not) – jbabey Jan 09 '13 at 16:12
  • 1
    Oh, I see. It's meant for the case 5 is replaced by something dynamically computed, I suppose. – Denys Séguret Jan 09 '13 at 16:14
  • It was initially meant for `if (settings.elementID && var element = document.getElementById( settings.elementID ) && !element.getAttribute('data-added')`, I just stripped it down for Q. – tomsseisums Jan 09 '13 at 16:16
  • This line is long enough... You could simply declare and assign the var at first line and test it at the following line. – Denys Séguret Jan 09 '13 at 16:18
  • Well, after getting the proof that it's not possible, I did return back to normal way. – tomsseisums Jan 09 '13 at 16:20

3 Answers3

4

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

But, an assignment statement returns true, so you can use:

var $variable;
if($variable = 5) {
    alert($variable);
}
ATOzTOA
  • 34,814
  • 22
  • 96
  • 117
2

var variable should be at the start of the function block, not inside an expression.

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

Of course, it's completely redundant...

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

You could declare the variable variable before the if clause:

var variable;

if (variable = 5)
{
    console.log( variable ); // logs 5
}
Sirko
  • 72,589
  • 19
  • 149
  • 183