This page looks best with JavaScript enabled

Quickly Initiate Objects in Javascript

 ·   ·  ☕ 1 min read

Initializing objects can be a pain. You may end up with multiple checks if you are trying to set a specific prop in the object path to a pre-defined value.

For e.g. set color of a Kawasaki bike to ‘blue’. To do this we have to traverse through the object path from the root through color. This may be made more difficult if you may or may not get a partial array from an external function or a third party system.

Similar to using an OR condition to initialize a variable, we can deploy an AND function to efficiently set a prop in an object path.

1
2
3
4
5
const vehicle = {};
(vehicle["bike"] = {}) && (vehicle["bike"]["kawasaki"] = { color: "blue" });

console.log("vehicle: ", vehicle);
// vehicle:  { bike: { kawasaki: { color: 'blue' } } }

The same arrangement will work even if you get a partial object from somewhere and you still need to output the same structure.

1
2
3
4
5
6
const vehicle = { bike: {} };
(vehicle["bike"] = {}) && \
    ((vehicle["bike"]["kawasaki"] = { color: "blue" }));

console.log("vehicle: ", vehicle);
// vehicle:  { bike: { kawasaki: { color: 'blue' } } }
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things