Detecting null or undefined

So far, we've covered how to independently check for both undefined and null, but we may want to check for both at the same time. It's quite common, for example, to have a function signature that has an optional argument. And if that argument is not passed or is explicitly set to null, it's normal to fall back to some default value. This can be achieved by explicitly checking for both null and undefined, like so:

function printHello(name, message) {
if (message === null || message === undefined) {
// Default to a hello message:
message = 'Hello!';
}
console.log(`${name} says: ${message}`);
}

Often, since both null and undefined are falsy values, it is quite normal to imply their presence by checking the falsiness of a given value:

if (!value) {
// Value is definitely not null and definitely not undefined
}

This, however, will also check whether the value is any of the other falsy values (including, false, NaN, 0, and so on). So, if we want to confirm that a value is specifically null or undefined, and no other falsy value, then we should stick to the explicit variation:

if (value === null || value === undefined) //...

Even more succinctly, however, we can adopt the abstract (non-strict) equality operator to check for either null or undefined since it considers these values to be equal:

if (value == null) {
// value is either null or undefined
}

Although this utilizes the generally frowned-upon abstract equality operator (which we'll explore later in this chapter), it is still a popular way to check for both undefined and null. This is due to its succinct nature. However, adopting this more succinct check makes the code less obvious. It may even leave the impression that the author meant to check solely for null. This ambiguity of intent should leave us doubting its cleanliness. Therefore, in most situations, we should opt for the more explicit and strict check.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.151.220