Null, Undefined and NaN in JavaScript

Null, Undefined and NaN in JavaScript

JavaScript has a couple of extraordinary variable states which, if you only use JavaScript now and then, will always give you headaches. You just want to briefly change a value in the DOM or incorporate a plausibility check, but you are annoyed by the funny little yellow exclamation mark in the lower left corner of the browser. Here is a short summary of how to distinguish between null, undefined and NaN and check them reliably.

The value zero is relatively rarely generated by JavaScript operations themselves. However, it can be used to mark an “empty” status of a variable. This can easily be checked with the === operator:
var empty = zero;
if (empty === null) {…}
The value undefined often hits you against, among other things, when a variable is not declared, a function parameter is not passed or a non-existent object property is queried. In short, undefined is the equivalent of NULL in PHP. You can reliably check for this without generating a runtime error, only with typeof ():
if (typeof (unknown variable) == “undefined”) {…}
When it comes to object properties or variables that have already been safely declared, the direct comparison also works (without quotes):
var ob = {};
if (ob.unbekannteeigenschaft == undefined) {…}
var empty;
if (empty == undefined) {xxx}
This can also be used to generate optional function parameters with default values:
function alertNumber (number)
{
if (number == undefined) number = 0; // Outputs 0 if argument was not given
alert (number);
}
In the first variant, if (unknown variable == undefined) {…} would not work, since a runtime error is triggered even before the comparison, namely when evaluating unknown variables.

JavaScript always spits out the value NaN (Not a Number) when a value that is not a number is used in a numerical context. There is the isNaN () function, but it not only checks for the specific value NaN, but also returns true for e.g. isNaN (“foo”). The specific NaN value can only be checked with a trick:
var num = parseInt (“Hello”);
if (typeof (num) == “number” && num + “” == “NaN”) {…}
In various forums you can always find tips to check for zero, undefined or NaN with a simple if (variable) {…}, which does not work, for example, with an integer with the value 0 or an empty string.

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,