Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the full form of an expressionless statement in javascript? [duplicate]

Tags:

javascript

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.

like image 844
Ian Boyd Avatar asked Feb 22 '14 14:02

Ian Boyd


1 Answers

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.

like image 152
cookie monster Avatar answered Oct 26 '22 06:10

cookie monster