This page looks best with JavaScript enabled

Store your metadata for free in Javascript

 ·   ·  ☕ 2 min read

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 -

1
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 -

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

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

1
2
3
4
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things