W3C.US

  • Increase font size
  • Default font size
  • Decrease font size
Home Experience Javascript Check if it is null

Check if it is null

E-mail Print PDF

As we known, null has no property, we cannot get its existence, and if we access null.property, got an error, but not an undefined

To consider the code below:

if (node.nextSibling.className == ...) {
   ...
}

If node is null, or node.nextSibling is null, the sentence will return error.

So the temporary solution is:

if ((node) && (next = node.nextSibling) && ... ) {
   ...
}

But if the depth is deeper, the conditional statement would be longer:

if (
(node) &&
(node.nextSibling) &&
(node.nextSibling.className == ...)
... )  {
   ...
}

The code would be ugly for a deep node.

To solve it, we can use a "trick" code like this:

if ( next = (node || 0).nextSibling) ) {
   ...
}

So the above code can be rewritten as:

if (((node || 0).nextSibling || 0).className == ...) {
   ...
}

Of course, this example should be suitable for personal development. If the project is maintained by many people, a framework is preferred.