-2

I am doing some null checks in my angular 8 code and had question on the best practices on checking for null and undefined.

My question is

Is the implicit if construct enough. Does it take care null and undefined

For e.g

Is

if(data) 

same as

if(data==null && data=='undefined') 
Mustapha Larhrouch
  • 3,279
  • 2
  • 11
  • 27
Tom
  • 5,859
  • 24
  • 87
  • 182
  • 4
    Try it and see? – Nicholas K Sep 12 '19 at 11:00
  • Does this answer your question? [JavaScript checking for null vs. undefined and difference between == and ===](https://stackoverflow.com/questions/5101948/javascript-checking-for-null-vs-undefined-and-difference-between-and) – Igor Apr 06 '20 at 15:55

4 Answers4

1

To answer your question, if will not implicitly take care of null and undefined case but, by-default any non-initialized variable in Javascript is undefined and not the string 'undefined'. So, in your case, 'data' will be undefined.

You may please check the below to explore and learn more...

let data;
if(data) {
  console.log('INSIDE IF: ', data);
} else {
  console.log('INSIDE ELSE: ', data);
}

if(data === null && data === undefined) {
  console.log('INSIDE IF with Comparison Check: ', data);
} else {
  console.log('INSIDE ELSE with Comparison Check: ', data);
}

If you try to execute the above code with strict equality operator (===), you will see the "INSIDE ELSE with Comparison Check" is called. This is the default way, JS works.

R. Richards
  • 21,615
  • 9
  • 55
  • 58
nimpossible
  • 342
  • 2
  • 11
0

undefined is a keyword, not string,

So, if(data) is same as if(data==null && data==undefined)

Adrita Sharma
  • 17,967
  • 8
  • 40
  • 61
0

With if(data) You check for truthyness. null and undefined are falsy, but also an emptry string '' is falsy. If you are searching for an actual value within the string, then use the truthyness.

MoxxiManagarm
  • 5,582
  • 2
  • 6
  • 36
0

if(data) is equivalent to:

if (data === null || data === undefined)

null and undefined are the same values but different types.

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

Here is some info on null vs undefined: http://tetontek.com/coding-best-practices/null-typing/

Jeff
  • 93
  • 4