The fastest way to look for object properties


  Hey there! This article is being published a "work in progress," which means that it is not done. So take everything with a grain of salt.

I may or may not come back and finish this article. Regardless, I hope that it's helpful in its current state.

I manage a library called onkey-event-manager that helps users map functions to keyboard actions. Part of the library is a validation step that looks for properties on an object.

To make this step as performant as possible, I wanted to know what the fastest method for checking an object for a given property.

Contenders #

Object.hasOwnProperty() #

This is the built-in method for checking an object for properties. The only question is whether this method is more performant than other options.

const obj = {};

console.log(
obj.hasOwnProperty('test');
? 'exists'
: 'does not'
)
// -> 'does not'

Object[] #

By referencing the property on the object directly, you can let JavaScript’s type coercion to force a boolean.

const obj = {};

console.log(
obj.test
? 'exists'
: 'does not'
)
// -> 'does not'

Note: This method for checking a property will fail if the value at the given property is false/falsey (e.g. const obj = { test: false }). Since I can guarantee that case won’t happen, I can still use it.

About

My name is Sean McPherson (SeanMcP), and I am a software engineer based in Pittsburgh, PA. Here I write articles about programming for developers of all levels.