The NULL Object Hack

• 1 min read

Have you ever seen this?

foo.bar;

/** OUTPUT **/
//
// TypeError: Cannot read property 'bar' of null

Well, there is an easy solution:

if (foo && foo.hasOwnProperty('bar')) {
  baz = foo.bar;
} else {
  // Do something else
}

However, this is long and stupid, especially when working with large nested objects. Sometimes if error handling isn’t as important you can get away with this little one-liner.

// Prevent null reference by making sure an object exists
baz = (foo || { }).bar;

// Or, using ternary operation (more robust but longer)
baz = foo && foo.hasOwnProperty('bar') ? foo.bar : 'default value';

The || means that the second option will be used if the first one is a falsy value (false, null, 0, etc). This method works well if you’re expecting foo to be an object that may not exist, but I don’t recommend using it in many other circumstances.

If you enjoyed this tutorial, please consider sponsoring my work on GitHub 🤗

Be the first to cheers
Now look what you've done 🌋
Stop clicking and run for your life! 😱
Uh oh, I don't think the system can't handle it! 🔥
Stop it, you're too kind 😄
Thanks for the love! ❤️
Thanks, glad you enjoyed it! Care to share?
Hacker News Reddit

×

Recommended Posts ✍🏻

See All »
• 3 min read
✨ HTML Share Buttons
Read Post »
• 3 min read
🚅 Next Stop, Yaak
Read Post »
• 4 min read
💻 Wait for User to Stop Typing, in JavaScript
Read Post »