Explain Codes LogoExplain Codes Logo

How do I check if an object has a specific property in JavaScript?

javascript
prompt-engineering
functions
callbacks
Anton ShumikhinbyAnton Shumikhin·Sep 19, 2024
TLDR

When you need to check if a JavaScript object possesses a specific property, the straightforward approaches are using 'prop' in myObj or myObj.hasOwnProperty('prop'). Note that the in operator returns true if the property can be found anywhere within the object's prototype chain. In contrast, the hasOwnProperty() method only verifies if a property is directly attached to the object under question.

'prop' in myObj; // Turns out to be true if 'prop' is anywhere within myObj's prototype chain myObj.hasOwnProperty('prop'); // Stays true only if 'prop' is a direct part of myObj

In the cutting edge of JavaScript, the Object.hasOwn(myObj, 'prop') method is growing in popularity because of its reliability even with objects bereft of a prototype, such as those produced using Object.create(null).

Evaluating property presence in every scope

Object.hasOwn(): The new sheriff in town

With the advent of newer ECMAScript standards, Object.hasOwn() has surfaced as a handy tool in situations where hasOwnProperty() might be tricky to use, for example:

  • Dealing with objects having a null prototype
  • Trying to bypass an overridden hasOwnProperty

Good ol’ reliable 'in' keyword

````'prop' in myObj``` is your friend for times when you need to check the presence of properties that might be inherited via the prototype chain.

Example:

function Vehicle() { this.wheels = 4; // Born with wheels, it's a vehicle thingy! } Vehicle.prototype.engine = 1; // Inherit an engine, we aren't making a cart, are we? const car = new Vehicle(); console.log('wheels' in car); // true, cars need wheels to roll! console.log('engine' in car); // true, unless you're Fred Flintstone

We do not speak of typeof

It's not recommended to use statements like typeof myObj.prop !== 'undefined' because they lead to false positives when the property exists but holds an undefined value. That’s like saying a fridge isn't there just because it's empty!

Undefined? It's just a phase! You can handle it

When defining functions, you can protect undefined from being redefined by setting a default parameter:

function isPropertyUndefined(obj, prop) { let undefined; // I define undefined 😎 return obj[prop] === undefined; }

Or simply use a self-invoking function to prevent undefined from misbehaving:

(function(undefined) { // Your code just taught undefined a lesson! })();

Tricky territories and remedies

When inheritance gets confusing: 'prop' in myObj VS Object.hasOwn()

Boundary issues aren’t fun. Determining inherited properties with 'prop' in myObj gets confused with directly owned properties, unlike Object.hasOwn() or myObj.hasOwnProperty().

Prototype pollution and how to cut to the chase

A straight call to hasOwnProperty, like Object.prototype.hasOwnProperty.call(myObj, 'prop'), can sidestep the possible hiccups that prototype pollution throws at you.

Juggling with Lodash and Underscore.js?

For the folks over at lodash and Underscore.js, the _.has(myObj, 'prop') function is a life saver. Why reinvent the wheel when you can relax and sip your coffee?

Keep your code shiny and working

As you brave through the world of property checks in JavaScript, keep these in mind:

  • Performance matters: Opt for the least resource-intensive query for your sanity.
  • Readability counts: Make your fellow programmers sing praises of your clean code.
  • Stay updated: Hold hands with the latest ECMAScript standards and rock that code!

In a nutshell: scenarios and guidelines

Mind the environment

Keep your code environment-friendly. Browsers or JavaScript engines can have unique compatibility quirks. The more the merrier?

Dealing with null prototype objects: Object.hasOwn to the rescue

While facing objects that could have a null prototype, always wield Object.hasOwn() for failsafe checks.

Performant rain check

For that killer performance, limit your property checks — especially inside loops or recursive functions. Remember, less is more!