Question:
I found the next code, and I got the impression it didn't make much sense.
function (data) {
if (data != null && data !== undefined) {
// codigo
}
}
From here, three different scenarios can happen:
-
The function is called with no arguments, making
data
an undeclared variable (and resulting in an error evaluatingdata != null
). -
The function was called specifically with
null
, orundefined
, in which case thedata != null
already protects the internal code, making the second condition irrelevant. -
The function was called with a non-null argument, and if it passes the test, both conditions are true.
Is there any scenario where it makes sense to keep the second condition?
Answer:
You're right, it doesn't make much sense. About each of the points you raised:
The function is called with no arguments, making data an undeclared variable (and resulting in an error evaluating data != null).
There is actually no such scenario. data
is always declared inside the function as it is a named argument. If you call the function without passing anything, it gets the value undefined
.
The function was called specifically with a null argument, or undefined, in which case the data != null condition already protects the internal code, making the second condition irrelevant.
True, data != null
returns false
if data
is null
or undefined
(and only then).
The function was called with a non-null argument, and if it passes the test, both conditions are true.
Right.
Is there any scenario where it makes sense to keep the second condition?
No 🙂 Unless you use strict equality operator ===
, which considers types. With ==
, any comparison with null
or undefined
is true if the other side is also null
or undefined
. That is, they are interchangeable with ==
. Therefore:
if (data !== null && data !== undefined)
it is the same as:
if (data != null)
it is the same as:
if (data != undefined)