Set Default Value of JavaScript Object Attributes

Set default value of Javascript object attributes

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.

Set the default value for the object in javascript

You can use Object.assign to create an object with default values:

const defaults = {  a: 1,  b: 2,  c: 3}
const obj1 = { a: 11 }const obj2 = { a: 11, c: 33}const obj3 = { a: 11, b: 22, c: 33 }
const newObj1 = Object.assign({}, defaults, obj1);const newObj2 = Object.assign({}, defaults, obj2);const newObj3 = Object.assign({}, defaults, obj3);
console.log(newObj1);console.log(newObj2);console.log(newObj3);

Set default value of property of object passed on parameter to function

just check it and set it:

export const Map: FunctionComponent<MapProps> = function Map({
settings,
}) {
settings.rotation = (settings.rotation || settings.roation === 0) ? settings.rotation : 360

How to set default value for Function object?

Yes, you can write something like:

function CountOfFruit(bowl){
this.strawberries = bowl.strawberries || "there is none";
this.blueberries = bowl.blueberries || "there is none";
}

In that way, if one of the attributes is null or an empty string, the default value will be used.

How can I assign default values to all undefined properties of an object being passed as a function parameter?

Try spread operator:

function x(obj1 = {}) {
let defaultObj = {foo: 'bar', fizz: 'buzz',...obj1};
console.log(defaultObj);
}

x({foo: 10});

Setting default values for properties in Javascript

You can set default properties in es6 when you declare params in your constructor like this constructor(p1 = 'Default Variable',p2 = 'Default Variable',p3 = 'Default Variable',p4 = 'Default Variable')



Related Topics



Leave a reply



Submit