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
🚅 Next Stop, Yaak
Read Post »
• 3 min read
⛰ïļ 2022 Recap: Getting Physical
Read Post »
• 5 min read
ðŸŠī Home-Grown Web Analytics
Read Post »