How to always return a default value for an object property in javascript?

Standard

Hi Guys,

Do you have a need where you want to return something as a default value if your JS object don’t have that property?

Let’s come to our problem.

Lets take an object (kind of a key value configuration object) which is coming from server and we need to make some very important decision based on this data.

var electricalConfig = {
  isLightOn: true,
  isBoardSmart: false,
  noOfSwitch: 10,
  noOfSockets: 3,
  isConnected: true
};

Above object basically tell us about the property of a smart electrical instrument. Lets say some of the same instruments has a special property which is "operateOnVolts" which can be present with in the object or not.

Our target is to return value for this property to 240 Volts if nothing has been provided.

We need some kind of way where we can define our condition something like this.

return electricalConfig[prop] ? electricalConfig[prop] : 'default'

Solution.

What if we can override Object’s default functions? Answer is YES!

we have a solution. Its Proxy.

The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).

In simple words, this is something like overriding the objects function.

Proxy is ES6 feature and not supported in older browsers. You can check compatibility on https://caniuse.com

I am assuming that you know about getter and setter of an object. By using setter and getter we can define a way of setting and getting property of an object.

In this case I need a way where I can catch the getter execution for my asked property and can decide what I want to do with that.

Lets see how we can do that.

var electricalConfig = {
  isLightOn: true,
  isBoardSmart: false,
  noOfSwitch: 10,
  noOfSockets: 3,
  isConnected: true
};

//we will create a proxy
var electricalConfigProxy = new Proxy (electricalConfig, {
   get: function (obj, prop) {
     if (prop == 'operatesOnVolts') // we can capture execution here
        return obj[prop] ? obj[prop] : 240; //we can set logic here
     return obj[prop]; // all other cases
   }
});

//now we will use proxy object to refer electricalConfig.

console.log (electricalConfigProxy.isLightOn); //true
console.log (electricalConfigProxy.operatesOnVolts); 240

Another useful example can be like below

// logger.js
var type = {
  "login": "LOGIN",
  "activate": "ACTIVATE",
  "registration": "REGISTER"
};

function Logger () {
  this.type = type;
}

function addLog (_type, message) {
  console.log ('log for type ' + _type + ' has been added');
}

// otherfile.js

var logger = new Logger ();

logger.add (logger.type.login, 'some messages');
// above will print
//log for type LOGIN has been added.

logger.add (logger.type.NEW_TYPE, 'some new messages');
// above will print
//log for type undefined has been added.

In above case, only three types of log messages can be added. it will return undefined in all other cases. We can solve this as below.

// logger.js
var type = {
  "login": "LOGIN",
  "activate": "ACTIVATE",
  "registration": "REGISTER"
};
var typeProxy = new Proxy (type, {
  get: function (obj, prop) {
    return obj[prop] ? obj[prop]: prop;
    // we will return prop-
    //value in case of property doesn't exist.
  }
});
function Logger () {
  this.type = typeProxy; // we will use propxy now
}

function addLog (_type, message) {
  console.log ("log for " + _type + " has been added");
}

// otherfile.js

var logger = new Logger ();

logger.add (logger.type.login, "some messages");
// above will print
//log for type LOGIN has been added.

logger.add (logger.type.NEW_TYPE, "some new messages");
// above will print
//log for type NEW_TYPE has been added.

You can read out whole documentation on Mozilla’s developer website here.

Please let me know if this article has solved your problem.

Thanks.

S with 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s