Is there any subtle difference between
if(myVar === undefined) {
// whatev
}
and
if(!myVar) {
// whatev
}
and if so which one is the best practice ?
Is there any subtle difference between
if(myVar === undefined) {
// whatev
}
and
if(!myVar) {
// whatev
}
and if so which one is the best practice ?
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.
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
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