Objects in Javascript are very interesting and extremely frustrating. They are very powerful in everyday development in JS, and provide a great interface for a multitude of grouping and interface creation. Despite all these great things, its confusing and can easily surprise you.

In these surprises, you can find some usueful tricks that can make your much more performant and readable. One of these being, bookmarking your position in an object. Let’s take a quick look at an example of an JS object.

let testObject = { test: {}, test2: [] };

Seems like a very simple object with two properties. One empty object, and one empty array. Nothing fancy, but a a great example to thoroughly explain what bookmarking is. To start things off, let’s start by bookmarking the object property test.

let bookmark = testObject.test;
console.log(stringBookmark);
// {}

As you see above, setting our new variable to the specified property on the testObject object assigns that value to it. So when you call on that new variable, it will return the value set for property on the object. Simple, easy, and nothing too difficult to understand! If recieving is so easy, modifying has to be equally as simple. Let’s look.

bookmark.testProp = 'hi';
console.log(bookmark);
// {testProp: 'hi'}
console.log(testObject.test);
// {testProp: 'hi'}

Yup! When we added a new property to the object by way of our bookmark variable, it updated there and the original source we defined it from. This also works the same in the event the object is updated directly on the source, or through the bookmark reference.

So now, we can view that variable as a ‘bookmark’ to that particular property on that object. We can not only use it to be an easy access point to the source value, but also a modifier as well. Now if modifying was so simple, reassigning should work the same way right. Let’s see.

bookmark = {};
console.log(bookmark);
// {}
console.log(testObject.test);
// {testProp: 'hi'}

Nope! What we did was assign the value of bookmark to a new object, and by doing so, removed the link it had to the object property we declared it’s initial value from. So when we look at them, the bookmark now returns our new object while the original stays the same. This same behavior can be expected for our array prop as well.

let arrayBookmark = testObject.test2;
arrayBookmark.push(5);
console.log(arrayBookmark, testObject.test2);
// [5] [5]
arrayBookmark = [];
console.log(arrayBookmark, testObject.test2);
// [] [5]

This is all possible because JS has two ways of assigning values, by reference or value. In a later article we’ll go over assigning in depth, as well as a more detailed approach as to how bookmarking can improve your code performance and readability.

For now though, take this quick example and start playing around with it in your codebase. Just not for only the sake of doing it because you like, but because it makes sense to use!