Explain Codes LogoExplain Codes Logo

Check how to determine if an object exists in JavaScript

javascript
existence-check
javascript-objects
null-check
Anton ShumikhinbyAnton Shumikhin·Jan 5, 2025
TLDR

First off, here's the quick way to check if a property is present in an object:

  • in operator can check for any property, even inherited ones:
if ('key' in obj) { /* exists, or maybe it's a ghost? */ }
  • .hasOwnProperty method checks for the object's own properties, not those spooky inherited ones:
if (obj.hasOwnProperty('key')) { /* exists, and it's not adopted! */ }
  • Strict comparison is for those who need to ensure that a property actually exists and not just truthy:
if (obj.key !== undefined) { /* exists for real, no fooling */ }
  • Using typeof operator is a wise way to check if an object exists in JavaScript land. This technique is popular because it doesn't conjure up an error when the object hasn't made its grand debut yet:
if (typeof maybeObject !== "undefined") { /* exists, or maybe it's in stealth mode? */}

The nuances of existence in JavaScript

The magical powers of typeof

In JavaScript realm, typeof is a safe and reliable spell to inspect an object's existence:

if (typeof maybeObject !== "undefined") { /* exists, or so it seems... */}

This incantation ensures the spell won't backfire and erupt into a ReferenceError in case maybeObject doesn't exist.

It's a global world after all

To verify the existence of global objects, especially in a place as vast as a browser environment, you'd need to look into the window object:

if ('maybeObject' in window) { /* Global object exists, or is it a global conspiracy? */}

Treading the Null-path

A mere undefined check can be a trap. A value of null may trick you into thinking an object exists:

if (maybeObject != null) { /* not undefined nor null, but could be an impostor */}

Remember, null is the JavaScript's Bermuda triangle - a shocking place where types disappear.

Digging deeper – Not just existence

Checking for existence is rather superficial. What we need is a functional object, not just an empty shell. So, if the object exists, ensure that its key methods or properties are accessible too. Host objects can play tricks here!

if (maybeObject && typeof maybeObject.someMethod === "function") { // Object exists and is ready for action, let's roll! }

This way, you double-check that your object doesn't just exist; it's also ready for some action!

Remember, functionality beats mere existence - true in JavaScript, even truer in life.