9

There's a syntax that Javascript adopted from C where you can perform a logical check, without checking anything:

if (foo) { 
}

What is this equivalent to? Is it:

if (foo != null) { }
if (foo !== null) { }
if (typeof(foo) != 'undefined') { }
if (typeof(foo) !== 'undefined') { }
if (typeof(foo) != 'object') { }
if (typeof(foo) !== 'Object') { }

My actual motivation for asking is wanting to ensure that a member "exists" (that is to say, if it is null or undefined then it doesn't exist):

if (window.devicePixelRatio !== null)
if (window.devicePixelRatio != null)
if (!(window.devicePixelRatio == null))
if (!(window.devicePixelRatio === null))
if (!(window.devicePixelRatio == undefined))
if (!(window.devicePixelRatio === undefined))
if ((window.devicePixelRatio !== undefined))

My concern is if the member is defined, but defined to be null, in which case (as far as i'm concerned) it's not assigned.

I know that the expressionless syntax returns true for a "truthy" value. I'm less interested in a "truthy" value, as an actual value.

Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
  • Note that foo also returns false if it is defined and equal to `0`. – XCS Feb 22 '14 at 14:57
  • @Cristy In which case it is a valid value :) – Ian Boyd Feb 22 '14 at 15:03
  • @IanBoyd, it is valid but the `if` is not executed. `var foo = 0; if(foo) console.log(1)` will output nothing, so it is not equivalent with any of those. – XCS Feb 22 '14 at 20:03

1 Answers1

6
if (foo) { 
}

"What is this equivalent to?"

It's not equivalent to any of the ones you suggested. It would be equivalent to:

if (Boolean(foo)) { }

or the same thing by using the ! operator:

if (!!foo) { }

or you could be explicit in your comparison if you really want.

if (!!foo === true) { }

"My actual motivation for asking is wanting to ensure that a member "exists"..."

To find if a member exists in an object, use the in operator.

if ("devicePixelRatio" in window) { }

"... (that is to say, if it is null or undefined then it doesn't exist):"

To check for not null or undefined, which is no the same as not existing, do this:

if (window.devicePixelRatio != null) { }

The != operator will perform both a null and undefined check at the same time. Any other value will meet the condition.

cookie monster
  • 10,671
  • 4
  • 31
  • 45
  • And we just got through being told that [`!=` should not be used](http://www.jshint.com/). *Le sigh* – Ian Boyd Feb 23 '14 at 20:45
  • @IanBoyd: Yeah, just like any feature, one should understand how it works and use it when appropriate. The semantics of `==` and `!=` can be a little confusing, but this is one particular case where it's very simple and helpful. Nothing is `== null` or `== undefined` except for `null` and `undefined`. You can configure jsHint to turn off that warning. – cookie monster Feb 23 '14 at 22:43