0

In PHP you could write this:

if(false !== ($value = someFunctionCall())) {
 // use $value
}

How would you write an equivalent of this in JavaScript without defining

var value;

before this comparison?

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
MyStream
  • 2,533
  • 1
  • 16
  • 33
  • 1
    You would not. An inline assignment (as a part of an expression) is different from a variable declaration. So, without using a global `value` variable, you can't. – Bergi Jul 24 '12 at 13:24
  • BTW, some-what related given the question: [Difference between using var and not using var in javascript](http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript) – Brad Christie Jul 24 '12 at 13:42

3 Answers3

1

You'd write

if (value = someFunction()) {

I don't trust my knowledge of PHP that heavily, but I suspect that explicit comparisons to false in if statements aren't necessary, as the expression is implicitly boolean. (edit — sometimes, if a function can return either an explicit boolean or some "good" value that evaluates to "falsy", then yes you do need the explicit comparison to boolean.)

edit — if you're squeamish about the ages-old confusion (or potential thereof) between = and ==, then I'd advise avoiding the construct entirely. There's nothing wrong with it, other than the fact that sometimes you want an equality comparison and sometimes you want an assignment.

edit oh also this presumes that "value" has been declared with var somewhere — if the question is about how you do the declaration in the context of an if statement, then the answer is that you cannot do that.

final edit I kind-of promise — to sum it up:

Assuming that "value" is declared:

var value;

somewhere, then:

if (false !== (value = someFunction())) { ... }

has pretty much the same semantics as the PHP original.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • that would be very bad practice – Lemex Jul 24 '12 at 13:24
  • I could write the above and not get a failure, but I would get an warning. That's the condition I'm attempting to work around. – MyStream Jul 24 '12 at 13:25
  • @LiamMcCann bad practice? Well, you could explicitly "booleanize" it I suppose. – Pointy Jul 24 '12 at 13:25
  • Yea that would be better, what im trying to say is if you do var value and its been used before it would error, but if you dont var it and value has been used before it would change the value of value and could cause issues other places in the code... Good answer though ! – Lemex Jul 24 '12 at 13:26
  • @LiamMcCann ah thanks - I've amended the answer to point out that the actual *declaration* of the variable has to happen before the `if` statement somewhere. – Pointy Jul 24 '12 at 13:28
  • @Pointy: The `===` exists for a reason. Suppose `if (!($a = strpos('foo','foobar')))` vs. directly comparing for `false`. (`strpos` would return a falsy `0`, however 0+ would be an acceptable result.) – Brad Christie Jul 24 '12 at 13:28
  • @BradChristie yes I understand that it's sometimes necessary, though (since we're on the general topic here :-) it seems like there's a code smell somewhere around that. You're right however, sometimes it really is necessary to check for an explicit boolean. – Pointy Jul 24 '12 at 13:29
  • The above PHP allows for a default condition of exactly false, but 0 or other values may be returned if not false. In JS, I wasn't sure if you could write a similarly compact check and assign without setting a variable somewhere first with var x=y; – MyStream Jul 24 '12 at 13:30
  • @MyStream OK I see what you're getting at - yes, and it would look almost exactly the same - JavaScript has `!==` with pretty much the same meaning. – Pointy Jul 24 '12 at 13:31
  • I think the simple answer is that it can't be done with an IF, can be done with FOR, can't be done with WHILE – MyStream Jul 24 '12 at 13:51
0

You can just have it assign when it's executed and JavaScript will automatically add the var declaration:

function foo(){
    return (Math.random() * 0.5) > 0;
}
if (false !== (f = foo())){
    alert('True!');
}
alert('f=' + f.toString());

jsFiddle Example

However, this is very bad practice. You should always declare your variables when and where you need them first. Just because PHP and JS accept this syntax doesn't mean it's good practice. The proper style would be as follows:

var f = false;
if (false !== (f = foo())){
    alert('True!');
}
alert('f=' + f.toString());
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • I'm looking at dependency injection. I don't have a problem defining them, just looking for a more compact way to write a statement and wasn't aware if there was one. – MyStream Jul 24 '12 at 13:27
  • There is no automatically inserted variable declaration, that's Coffeescript. In JS, this would use a global variable. – Bergi Jul 24 '12 at 13:29
  • @Bergi: I never implied where it would scope the variable, just that JS acknowledges it should be a variable and declares it (implicitly). – Brad Christie Jul 24 '12 at 13:30
  • So, in essence, it's not possible to formulate an inline assignment as part of something like while or if/else or switch. It has to be done before hand regardless. – MyStream Jul 24 '12 at 13:36
  • @MyStream: Yes. The only block I'm aware of where JS allows declaration within (without getting in to code practices) is the `for`: `for (var i = 0; i < 10; i++){ /* i */ }`. Other than that, declare before use is necessary. Again, all is dependent on how readable you want code and if you care about good practices. (**EDIT**: If you _really_ want to get in to it, PHP and JS are alike in terms of variable declarations [less the var keyword]) – Brad Christie Jul 24 '12 at 13:38
  • It was this condition I had in mind. For allows it, but IF didn't appear to, so I was curious. The condition usually allows for statements to be single-lined where the variable is created, assigned and compared and then used in that block and usually unnecessary in the else block, but it means, in php, that you create only at the last moment, and only if you need that space set aside rather than defining a lot of variables up front for all possible conditions that might follow. Use cases determine usability, but some cases make it a very readable php alternative, not necessarily js, perhaps – MyStream Jul 24 '12 at 13:44
  • @MyStream: From my perspective (and I agree about not declaring everything up-front, but only to an extent) a variable should be defined but only where it's scope is beginning (essentially adhering to [block scope](http://en.wikipedia.org/wiki/Scope_%28computer_science%29#Block_scope_within_a_function)). However, I will never let a condition declare the variable for me. A good example is [this](http://ideone.com/Emt2c). – Brad Christie Jul 24 '12 at 13:51
-1

That would be very bad practice in JavaScript,

You would be best to do

if(!(var value = someFunctionCall())) { // use value //}

Personally i would say define it before. Your call though. If you worried about memory then define it and null it after use.

Lemex
  • 3,772
  • 14
  • 53
  • 87
  • 1
    Implementation notwithstanding `null` does not take less memory than `false` in JavaScript. You can, however, use the `delete` keyword to remove a variable from memory. – Jordan Running Jul 24 '12 at 13:29
  • 1
    @Jordan: That's not how to use delete as well. This keyword is designed for properties only. – Bergi Jul 24 '12 at 13:31