0

I believe I have found cases where I need to check for both undefined and null for a javascript object as follows:

if (x !== undefined && x != null && x.length > 0) {...}

However, in a recent upgrade of JetBrains tools, it tells me that this is sufficient

if (x != undefined && x.length > 0) {...}

My question is, I'm just wanting to insure that a string "x" has a length of non-zero and is not undefined or null (with the least amount tests).

Thoughts?

gdoron is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
Peter Kellner
  • 13,491
  • 23
  • 89
  • 166

7 Answers7

5

in javascript

undefined == null // true
undefined === null // false

so checking with == for undefined makes the == check for null redundant.

gdoron is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
2

Try

if (x && x.length)

as undefined, null and 0 are all falsy values.

EDIT: as you seem to know that x should be a string, you can also just use if (x) as an empty string is also falsy.

Dennis
  • 13,680
  • 2
  • 33
  • 54
2

Checking if foo === undefined will trigger the error foo is not defined. See variable === undefined vs. typeof variable === "undefined"

The existential operator in CoffeeScript compiles to

typeof face !== "undefined" && face !== null

Edit:

Matt's comment is better if you only want to check for strings:

typeof x === 'string' && x.length > 0
Community
  • 1
  • 1
Wex
  • 15,188
  • 10
  • 59
  • 102
2

You can use _.isNull from Underscore a JavaScript library provides a whole mess of useful functional programming helpers.

_.isNull(object)

Returns true if the value of object is null.

_.isNull(null);
=> true
_.isNull(undefined);
=> false
Community
  • 1
  • 1
Alaeddine
  • 1,441
  • 2
  • 22
  • 44
2

This is what I use and it's the most concise. It covers: undefined, null, NaN, 0, "" (empty string), or false. We can therefore say that "object" is truthy.

if(object){
    doSomething();
}
James Drinkard
  • 14,670
  • 15
  • 108
  • 135
0

Try this

 if (!x) {
  // is emtpy
}
iJade
  • 21,874
  • 54
  • 150
  • 234
  • The case I'm almost always looking for and I'd like to have a really good "always use" pattern is Is it a non null, non empty string – Peter Kellner Aug 24 '13 at 19:45
0

To check against null AND undefined AND "empty string" you can just write

if(!x) {
   // will be false for undefined, null and length=0
}

BUT you need to be sure that your variable is defined! Otherwise this will cause an error.

If you are checking for a value in an object (e.g. the window object), you can always use that. E.g. for checking for localStorage support:

var supports = {
    localStorage: !!window.localStorage
}
jukempff
  • 955
  • 6
  • 12