Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value of Javascript object attributes

Tags:

javascript

Is there a way to set the default attribute of a Javascript object such that:

let emptyObj = {}; // do some magic emptyObj.nonExistingAttribute // => defaultValue 
like image 513
sandstrom Avatar asked Jul 06 '11 17:07

sandstrom


People also ask

What is default value of object in JavaScript?

In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value. This is where default parameters can help. In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined .

How do you assign default values to variables?

The OR Assignment (||=) Operator The logical OR assignment ( ||= ) operator assigns the new values only if the left operand is falsy. Below is an example of using ||= on a variable holding undefined . Next is an example of assigning a new value on a variable containing an empty string.

How do you set the value of an object?

To change the value of an existing property of an object, specify the object name followed by: a dot, the name of the property you wish to change, an equals sign, and the new value you wish to assign.

What is the default value of object variable in Java?

Objects. Variables of any "Object" type (which includes all the classes you will write) have a default value of null.


2 Answers

Since I asked the question several years ago things have progressed nicely.

Proxies are part of ES6. The following example works in Chrome, Firefox, Safari and Edge:

let handler = {   get: function(target, name) {     return target.hasOwnProperty(name) ? target[name] : 42;   } };  let emptyObj = {}; let p = new Proxy(emptyObj, handler);  p.answerToTheUltimateQuestionOfLife; //=> 42 

Read more in Mozilla's documentation on Proxies.

like image 53
sandstrom Avatar answered Sep 21 '22 17:09

sandstrom


Use destructuring (new in ES6)

There is great documentation by Mozila as well as a fantastic blog post that explains the syntax better than I can.

To Answer Your Question

var emptyObj = {}; const { nonExistingAttribute = defaultValue } = emptyObj; console.log(nonExistingAttribute); // defaultValue 

Going Further

Can I rename this variable? Sure!

const { nonExistingAttribute: coolerName = 15} = emptyObj; console.log(coolerName); // 15 

What about nested data? Bring it on!

var nestedData = {     name: 'Awesome Programmer',     languages: [         {             name: 'javascript',             proficiency: 4,         }     ],     country: 'Canada', };  var {name: realName, languages: [{name: languageName}]} = nestedData ;  console.log(realName); // Awesome Programmer console.log(languageName); // javascript 
like image 45
alexdriedger Avatar answered Sep 21 '22 17:09

alexdriedger