0

I have some javascript that uses query selector

let testobj;
testobj = document.querySelector('#someobject');

If I write the next line as below it doesn't enter the if

if (testobj !== null && testobj !== 'undefined')

If it is written as below it does

if (testobj != null && testobj != 'undefined')
MicroMan
  • 1,988
  • 4
  • 32
  • 58
  • With `!=` you only need one comparison. The values `null` and `undefined` are treated the same with `!=`. – Pointy Jan 07 '20 at 15:56
  • 1
    Also `.querySelector()` will never return `undefined` anyway. – Pointy Jan 07 '20 at 15:58
  • 2
    Do you mean `testobj !== 'undefined'` or `testobj !== undefined`? – Bergi Jan 07 '20 at 15:58
  • 1
    [Which equals operator (== vs ===) should be used in JavaScript comparisons?](https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons) – Andreas Jan 07 '20 at 15:58
  • `if (testobj !== null && testobj !== undefined)` is equal to `if (testobj != null)`, if that's what you're asking. – Bergi Jan 07 '20 at 15:59
  • 2
    `'undefined'` is not the same as the `undefined` keyword – Rory McCrossan Jan 07 '20 at 15:59
  • There's no reason whatsoever in this case to worry about `undefined`. Generally however `!=` is useful because in many situations `null` and `undefined` are semantically equivalent. – Pointy Jan 07 '20 at 16:01
  • @DOCTYPEHTML — They aren't. Its `!==` they are using. Anything can be NOT two different things. – Quentin Jan 07 '20 at 16:04
  • @DOCTYPEHTML He is asking that it be exactly _not_ two different values which is possible. For example, 2 is not 3 and 2 is also not 4. – nurdyguy Jan 07 '20 at 16:05
  • ==/!= checks value only, ===/!== checks value and type – Evik Ghazarian Jan 07 '20 at 16:43

2 Answers2

2

You are confusing two conventions for comparison with undefined:

 x === undefined

and

 typeof x === 'undefined'

Thee former used to be considered poor style because undefined was simply a variable, which when used before initialization had the value undefined, which could however be changed to anything, including null or even 3. With modern JS that's much less of a worry - undefined is now non-writeable, meaning you only really need to worry about the value of undefined inside of everyone's favorite JavaScript bugbear, with blocks.

For backwards compatibility, sometimes typeof x === 'undefined' is preferred, but in modern practice x === undefined is fine. However, if you are comparing x against both null and undefined, x != null is IMO clearer and more concise, although some people do advocate never using == and != in JavaScript.

Evan
  • 174
  • 2
  • 10
1

When using !== for undefined you should not put it in quotes. So the code should look like:

if(testobj !== undefined)

Or you can use typeof to compare the quoted 'undefined', like this:

if(typeof testobj !== 'undefined')
Nawed Khan
  • 4,393
  • 1
  • 10
  • 22