Why do some developers use Object.prototype.hasOwnProperty.call()?

BSP object hasownproperty
Original photo credit: Pete Wright

You might have read someone else’s JavaScript code recently and came across something like this:

And you’re probably wondering like I did before I dug deeper, why not just use instance.hasOwnProperty('getName')? It’s much shorter code, which probably means it’s easier on the brain and less prone to errors, right?

Turns out, not really. There are two main reasons to invoke the hasOwnProperty that is on the original Object.prototype.

Reason 1: objects can be created with no prototype

The first reason is the one cited in ESLint‘s no-prototype-builtins rule.

This seemingly overly-verbose approach to checking for a property on an object is actually a fail-safe. Consider an object initialised using Object.create(null):

In the snippet above, we initialised a new object using Object.create(null). Because null was passed in, the result is an object that is void of the default object’s prototype chain. No prototype means no hasOwnProperty method.

Wondering why anyone would want a completely empty object instead of just initialising with the object literal {}? I did too. Apparently, it’s a way of simulating a Map data structure in JavaScript before it was introduced in ES6. This hack is not so often used now, but with all hacks, it’s good to know it exists, if only just to help us identify them when we see them.

Reason 2: prototype properties can be overridden

This one should be easier to understand. If something can be overridden, it’s safer to refer to the source of truth.

When we call the method that is directly on the object instance, we’re one degree (or more, depending on the class inheritance) separated from the original method defined on the Object class.

Yes, I agree that this is an unlikely scenario and that if it does happen on your team, it reveals a serious lapse of judgement of the developer responsible for it. As a rule, never override an in-built method on the prototype chain!

But if being slightly more verbose can eliminate the possibility of just one extremely hard-to-spot bug, I’d choose verbosity any day! As an aside, I think that’s a big part of what makes TypeScript popular among in the JavaScript community despite its lengthiness.

Use the source of truth on the Object.prototype

I hope that clears the air for you. The ESLint “no-prototype-builtins” rule was what made me realise this detail, but for you, it might well have been reading someone’s code.

Either case, let’s opt to use Object.prototype.hasOwnProperty.call() from now on. It’s just the better way of checking for a property.

How to clone class instance in JavaScript

One very common scenario for wanting to clone a class instance is inside a function.

Why there’s a need to clone objects/arrays inside functions

Because non-primitive data structures are passed by reference in JavaScript, we will inadvertently mutate the original object or array passed into a function as an argument. Here’s a quick illustration of this behaviour:

In the above, userJohn was mutated inside the maskSensitiveInfo() function. Specifically, the line user[field] = 'hidden'; mutates userJohn directly instead of mutating a copy of it.

This behaviour is expected for non-primitive data types; that is, any variables that hold a data type other than the 6 primitives (boolean, number, string, symbol, null, and undefined).

I think it’s also the reason why many JavaScript code style guides I’ve come across so far recommend not mutating arguments within functions. Airbnb’s style guide is an example.

How to shallow copy an object

Instead, they recommend creating a copy of any object/array inside functions – basically as a preventive measure to eliminate the potential for unwanted (and hard to trace) side effects caused by mutating something outside of the function from within.

In the above snippet, the maskSensitiveInfo() function now creates a copy of the user object being passed in and uses it for intermediate steps that mutate it, before returning it. That’s why userJohnMasked is no longer the same object as userJohn (ie. userJohnMasked === userJohn evaluates to false).

Caveat for shallow copy: only one level deep

What we’ve just seen is shallow copying. It’s so-called “shallow” because Object.assign() is only going to copy over the first-level values and assign that to a new object. If, for example, userJohn has a key called “account” and its value is another object, that object is not copied but is once again only referenced.

This snippet illustrates the point:

The original object, userJohn, is accidentally mutated by the line userClone.account.number = 'hidden'. This is one of those horrible bugs that can be really hard to pinpoint.

To do a deep copy (vis-a-vis shallow copy), it’s best to use an external library like jQuery or Lodash:

More details on deep cloning can be found in this SO thread.

So that’s how you shallow/deep clone objects created from using the object literal syntax var x = {}; or var x = Object.create();, meaning they are literally constructed directly from the Object class in JavaScript.

What about objects that are instances of a custom implemented class? As we’ll see, because we will most likely have methods implemented on custom classes, the methods above will not suffice – the instance methods will not be copied over!

Cloning a class instance including its methods

I recently found out something that wasn’t obvious to me – apparently, methods defined within a class definition are automatically added to the prototype chain of the instance object.

So, to copy over the methods from one class instance to another, we will need to copy the prototype chain on top of copying the instance variables.

Here’s the magical series of built-in methods that can be used to create a copy of an instance of a custom-implemented class:

That’s quite horrid syntax on first and second glance, but on third glance…

Here’s how it works:

  1. Object.create() creates a new object and Object.getPrototypeOf() gets the prototype chain of the original instance and adds them to the newly created object
  2. Object.assign() does as we’ve seen earlier, which is to (shallow) copy the instance variables over to the newly created object

This comes in really handy for custom-implemented classes like Stack or Queue or LinkedList.

However, sometimes you will need to add a few extra lines to the copyInstance() method, depending on whether your class has any instance variables that need to be copied as well. In my case, I had to clone an array that is stored as an instance variable called this.stack within the Stack implementation:

Here’s the use case I recently had with a Stack (it uses ES6, so in case you’re unfamiliar, just treat all const and let as vars):

Summary

I didn’t intend for this post to get so long, but I wanted to be complete with my examples because I know it’s important contextual information for wrapping your head around the idea of cloning.

Here’s a summary to make it easier:

  • Non-primitive data types like Objects and Arrays are passed by reference into functions, unlike for primitives which are passed by value
  • Passed by reference implies that if a function mutates or reassigns an argument that is an object or array, the original variable outside of the function also gets mutated/reassigned – this can become a nasty, hard to uncover bug
  • For the above reasons, Airbnb, among other companies, eschew direct mutation or reassignment of arguments within functions
  • The solution is to create a clone before working with the cloned variable inside the function to prevent side effects
  • There are two types of cloning: shallow and deep
  • Shallow only clones one layer deep, which means if any key-value pair in an object contains another object, or if an object is stored as an item in an array, those continue to be references instead of cloned values
  • Deep cloning accounts for nested objects by effectively creating copies recursively until the deepest layer, ensuring there are no connected references to the original object
  • To clone an instance of a custom-implemented class, including its custom-implemented methods within the class, you need to copy over the prototype chain (because methods defined inside a class are added to the prototype chain) as well as the instance variables

I’m mainly writing this to ensure I have a note on this esoteric but essential part of JavaScript, but I certainly hope it was helpful to you in some way too!


Enjoyed reading this? I’ve been writing posts like these revolving around technology, society, and life on and off for more than a year now. This year I’m aiming for 5 posts per week, and I’d love to have you join me on that personal journey. You can read more at my blog or subscribe to get the most interesting posts delivered to your inbox – it’s free.

Why implement Stack in JavaScript when you have Array?

This is the stupidly simple question I asked myself today as I was trying to familiarise myself with data structures. Is there ever a need to implement a stack data structure in JavaScript when the built-in Array data structure already exists?

Based on my short research, the answer is no – there’s probably no need to implement a separate Stack constructor function or class in JavaScript. Since Array already has the typical methods you’d need for a stack to work, like push() and pop(), you can just use an array to simulate a stack.

Continue reading “Why implement Stack in JavaScript when you have Array?”

Bubble sort explained

bubble sort explained banner
Photo by Sime Basioli on Unsplash

The goal of bubble sort is to sort an array in ascending or descending order according to a sortable property.

In our example below, we just use an array of integers to directly simulate the sortable property (a number), but in reality, you can imagine that that probably isn’t a frequent use case. What’s probably more common is sorting an array of objects by one of their properties, like IDs.

Continue reading “Bubble sort explained”

How to prevent jQuery from loading image in parseHTML

This post is inspired by a recent bug fix at work related to jQuery’s parseHTML() method.

I noticed multiple redundant calls to our server endpoint each time a user saves an email template using the drag-and-drop email builder of Metisa.

The bug, when traced to its end, was nothing like what I’d originally suspected. Because we use Backbone.js for the front-end model layer (to make API calls) with React.js as the front-end view layer, I had initially thought it was Backbone making redundant API calls.

Continue reading “How to prevent jQuery from loading image in parseHTML”

What is DRY (in programming)?

what is dry blog banner nickang showing weed growing on white wall
Photo by Ben Neale on Unsplash

Ever heard someone tell you that your code is not “DRY”? What’s the deal with that? Are they saying that your code can hold a lot of water…?

Sorry for the bad joke. DRY is an acronym, and it stands for Do not Repeat Yourself. As far as I can tell so far in my short career as a software engineer, this is one of the most revered principles in writing software.

In this post, we’ll explore why it’s important to keep your code DRY and in general, how you can go about doing it.

Continue reading “What is DRY (in programming)?”

How to implement a Linked List in JavaScript

implement linked list in javascript banner nickang
Photo by LinkedIn Sales Navigator on Unsplash

In this post, you’ll learn how to implement a linked list in JavaScript. This is the second part of a 2-parter post on linked lists (read part 1).

Let’s jump right in!

Continue reading “How to implement a Linked List in JavaScript”