Jammie Mountz

Software Engineer

Understanding Objects, Context, and Equality

To someone just starting to learn JavaScript, there’s a few concepts that are easy to trip up on – one of them being object equality and understanding them as contexts. To help, I’ve illustrated an example!

object variable diagram-01

Let’s think of Liz and Paul as objects

var liz = { has: "pizza1" }
var paul = { has: "pizza2" }

Sometimes when we see identical objects, we want to think they’re the same. In this example, they’re obviously not the same – it’s clear that Liz and Paul each have their OWN slice, they’re not sharing the same one.

liz === paul // returns false

However, variables CAN point to the same object.

var liz = { has: "pizza" }
var elizabeth = liz

All we’re doing is also pointing the variable elizabeth at the object stored in liz. These two objects are the same. You can test this by running equality –

liz === elizabeth // returns true

Variables pointing to objects can be useful when setting the context for a function. For example, let’s put a method on liz to see her slice of pizza.

liz.returnPizza = function() { return this.has; }

Because this is a method on liz, when it’s called, the “this” keyword binds to liz’s object and returns her slice.

liz.returnPizza() // returns "pizza1"

But you can call this function in the context of another object as well, using “apply.” Apply is a function that accepts a new context to run the function in.

liz.returnPizza.apply(paul) // returns "pizza2"

Hopefully this clarifies how objects can be used to set a context, and understanding their equality. When I was first learning JavaScript, I thought objects were just used as storage for data, similar to an array. And they are! But they also do so much more. 🙂

Fluent in Spanish and JavaScript, salsa dancer, lover of material design.

Living in San Francisco, CA