1

Is there any subtle difference between

if(myVar === undefined) {
  // whatev
}

and

if(!myVar) {
  // whatev
}

and if so which one is the best practice ?

Romuald
  • 205
  • 1
  • 13
  • myVar = false will enter the if in second case but not in first – apomene Jul 30 '20 at 12:09
  • 3
    Does this answer your question? [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) – Onur Arı Jul 30 '20 at 12:09
  • If you don't know the difference between falsy values and undefined in JS, you'd better stick to second approach. – glinda93 Jul 30 '20 at 12:09

3 Answers3

4

if(myVar === undefined) { // whatev }

This if statement will execute only if myVar is undefined.

Whereas the other statement:

if(!myVar) {
  // whatev
}

Will execute if myVar is undefined or null or false or 0 or "" or any other falsy value.

So based on your requirement. If you want to execute for only undefined values, select first option else go for the second one.

shubham
  • 1,289
  • 2
  • 12
  • 26
1

There is a huge difference.

if(myVar === undefined) {
  // whatev
}

only checks if it is really undefined

if(!myVar) {
  // whatev
}

checks for a falsy value, which could be 0, false, '', ,undefined, null or any other falsy value

An empty Array also can be a falsy value if you check

let arr = [];

if(!arr.length){} // falsy since the lenght is 0 which is falsy
critrange
  • 5,652
  • 2
  • 16
  • 47
Andre
  • 458
  • 5
  • 10
0

Yes there are the differences

let me explain you with example.

var myVar ; //just declared, so by default it has value undefined, undefined is a 
//primitive value automatically assigned to variables that have just been declared,

console.log(myVar === undefined) // this should print true
console.log(!myVar) // this should also print true as it converts it into truthy or falsy value

now suppose

var myVar = "" ; //declared and assigned empty string

console.log(myVar === undefined) // this should print false, as "" is not undefined
console.log(!myVar) // this should  print true as "" is converted into falsy value and negation convert it into truthy

read about falsy values and [undefined][2] in Java Script

TechnoTech
  • 744
  • 4
  • 14