Store your metadata for free in Javascript

What if you want to play around with data, but also maintain metadata at the same time? In Javascript you don’t have to create other objects or work hard for that Nirvana that someone in the office was talking about.

You just have to go ahead and store the darn metadata along with the object, and everyone is happy.

Consider this array -

const nums = [1, 3, 5, 7];

Let’s say you have to store a message along with the array. You might have seen distinct variables being assigned to serve such a need.

But, this is Javascript. You can do a simple -

Object.defineProperty(nums, "message", {
  value: "earth is headed towards mars"
});

You can now access the not-so-secret message independent of data.

console.log(nums);
// [ 1, 3, 5, 7 ]
console.log("nums.accessTime: ", nums.message);
// earth is headed towards mars

We knew this all along.

Let us level up by making this message a part of a transaction.

const nums = [1, 3, 5, 7];
Object.defineProperty(nums, "message", {
  value: "earth is headed towards mars",
  writable: true
});

const readableArr = (nums, message) => {
  const newArr = nums;
  function setMessage(message) {
    newArr.message = message;
    return newArr;
  }
  return setMessage;
};

let readNums = readableArr(nums);

const newNums = readNums("mars, here we come");
console.log("newNums: ", newNums);
console.log("newNums.message: ", newNums.message);

nums.push(9);
readNums("whoa");

console.log("newNums: ", newNums);
// [ 1, 3, 5, 7, 9 ]
console.log("newNums.message: ", newNums.message);
// whoa
};

All we have done is use closures to create two functions - one within the other. We call parent function, assign it to readNums and bring in another variable newNums when we begin transaction.

newNums points to our initial array nums, but also has the message contained. We can change this message without impacting the actual data.

The practical application for such metadata is to -

  • store data about a variable that is being used in a function
  • likely disposed off after the function

For e.g. count of the number of elements changed in transaction, an array of all changed elements, etc. These data points are important during a transaction but do not have a case to make them persistent.

comments powered by Disqus