-1

I have JavaScript method as below,

function showMsg(id) {
 if(id==null && id== undefined)
  //doing some task
}

this showMsg(id) is getting called from different event with id having some value but onLoad event its not required any parameter so I am calling this method as below on Onload event

function onLoading(){
    showMsg(null);
}

in Java Script if we have declare a variable and haven't assigned any value to it then it will be undefined.

My question is that is there any situation where if(id==null && id== undefined) will be false when get called as showMsg(null); from onLoading() method.

Will it cause any performance issue,and what are the pros and cons for using this type of check.

Any help suggsetion must be apprecaited Thanks in Advance.

JonyD
  • 1,237
  • 3
  • 21
  • 34
Zia
  • 1,001
  • 1
  • 13
  • 25
  • 6
    *"If `id` is `null` __and__ `undefined`"*? At the same time? That's never going to be the case. It only happens to work because you're using a loose `==` comparison, which matches all *falsey* values. You may as well just do `!id` for the same outcome. If you actually want to check for only `null` and `undefined` specifically you'll have to do `id === null || id === undefined`. – deceze May 25 '17 at 12:34
  • @deceze if i am making call like showMsg(null); in this use case will the condition if(id==null && id== undefined) become false? – Zia May 25 '17 at 12:42
  • @deceze `===` might break if variable doesn't exist in which, he has to use `typeof` – Mr. Alien May 25 '17 at 12:44
  • @Mr.Alien Since `id` is defined as a function parameter, it will exist. Only its value will be `undefined`. – deceze May 25 '17 at 12:45
  • @deceze fair enough.. just saying regardless of his code.. just going with the title.. – Mr. Alien May 25 '17 at 12:56

1 Answers1

1

Use if(var != null).

The != will make both checks: if not undefined and not null.

JonyD
  • 1,237
  • 3
  • 21
  • 34
  • 1
    check also this: https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in and this https://stackoverflow.com/questions/5101948/javascript-checking-for-null-vs-undefined-and-difference-between-and – JonyD May 25 '17 at 12:43