Set default value of javascript object attributes

javascript object default value
javascript default parameters object
javascript default value if undefined
es6 default parameters object
javascript destructuring default value
typescript destructuring default value
js object destructuring default value
javascript default value if null

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

var emptyObj = {};
// do some magic
emptyObj.nonExistingAttribute // => defaultValue

IE can be disregarded, Chrome Frame has relieved me of that headache.

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:

var handler = {
  get: function(target, name) {
    return target.hasOwnProperty(name) ? target[name] : 42;
  }
};

var p = new Proxy({}, handler);

p.answerToTheUltimateQuestionOfLife; //=> 42

Read more in Mozilla's documentation on Proxies.

Default parameters, Let's break down the 3 different ways to set Default Values using logical operator, ternary, and if/else Tagged with javascript, webdev,  As long as the 1st expression (left side) is truthy, it will always be the one selected. However, if the 1st expression (left side) is ever falsy, then the 2nd expression (right side) will be by default output. And that's why this || is known as the operator to set default values.

There isn't a way to set this in Javascript - returning undefined for non-existent properties is a part of the core Javascript spec. See the discussion for this similar question. As I suggested there, one approach (though I can't really recommend it) would be to define a global getProperty function:

function getProperty(o, prop) {
    if (o[prop] !== undefined) return o[prop];
    else return "my default";
}

var o = {
    foo: 1
};

getProperty(o, 'foo'); // 1
getProperty(o, 'bar'); // "my default"

But this would lead to a bunch of non-standard code that would be difficult for others to read, and it might have unintended consequences in areas where you'd expect or want an undefined value. Better to just check as you go:

var someVar = o.someVar || "my default";

3 Ways to Set Default Value in JavaScript, There's one last thing we need to know about destructuring objects, and that is the ability to set defaults. This one's a little bit confusing, so bear  In the example below, the default value for the country attribute should be an object with two properties: name and capital. At runtime, however, it defaults to the string " {'name':'France','capital':'Paris'}" and not an object.

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

Setting Default Values with JavaScript's Destructuring, , it goes by default into the global scope, which is window. How to set specific property value of all objects in a javascript object array (lodash) Set a default parameter value for a JavaScript function.

This sure sounds like the typical use of protoype-based objects:

// define a new type of object
var foo = function() {};  

// define a default attribute and value that all objects of this type will have
foo.prototype.attribute1 = "defaultValue1";  

// create a new object of my type
var emptyObj = new foo();
console.log(emptyObj.attribute1);       // outputs defaultValue1

Javascript: is the Windows object a default object?, has a default value of undefined. It means that if you don't pass the arguments to the function, its parameters will have the default values of undefined . Set a default parameter value for a JavaScript function. I would like a JavaScript function to have optional arguments which I set a default on, which get used if the value isn't defined (and ignored if the value is passed).

my code is:

function(s){
    s = {
        top: s.top || 100,    // default value or s.top
        left: s.left || 300,  // default value or s.left
    }
    alert(s.top)
}

The Beginner's Guide to JavaScript Default Parameters, Can you assign the default values to a function parameters? It does not set the default value during instantiation and doesn't impact autoproperties. From MSDN: A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value.

Default Parameters in Javascript, Don't use the || operator to set defaults​​ This pattern should be avoided in all languages. While using || works as intended when x is null or an actual object, it also sets the default value for other falsy values, such as false . false is a non-blank value that you never want to override with a default. 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.

JavaScript: Hash/Object with default value, What's happening here? We're doing the following: setting default values for both our parameters tag and config , in case they aren't  The values are written as name:value pairs (name and value separated by a colon). JavaScript objects are containers for named values called properties or methods. Object Definition

Clean Code with ES6 Default Parameters & Property Shorthands , This tutorial teaches you how to use JavaScript default parameters for functions and ES6 provides an easier way to set the default values for the parameters of a The value of the arguments object inside the function is the number of actual​  The attributes collection is iterable and has all the attributes of the element (standard and non-standard) as objects with name and value properties. Property-attribute synchronization. When a standard attribute changes, the corresponding property is auto-updated, and (with some exceptions) vice versa.

Comments
  • EVERY non existing attribute or just a KNOWN attribute name?
  • If you are planning to support Internet Explorer (before Edge), you're out of luck: caniuse.com/#search=proxy Also, polyfill github.com/tvcutsem/harmony-reflect doesn't support IE
  • Congrats, you've earned Phoenix (Gold Badge: answered one of your own questions at least a year later, with an answer that at least doubled the number of votes of the most popular answer)
  • Object.withDefault=(defaultValue,o={})=>new Proxy(o,{get:(o,k)=>(k in o)?o[k]:defaultValue}); o=Object.withDefault(42); o.x //=> 42 o.x=10 o.x //=> 10 o.xx //=> 42
  • So using Proxy also means Object.getEntries can't be called on a Proxy :(
  • If you mean Object.entries, you can modify the handler to set properties when they are accessed. Change return target.hasOwnProperty(name) ? target[name] : 42; to if (!target.hasOwnProperty(name)) target[name] = 42; return target[name];.
  • warning: var someVar = o.someVar || "my default"; will have potentially unexpected results when o.someVar is populated but evaluates to false (e.g. null, 0, ""). someVar = o.someVar === undefined ? o.someVar : "my default"; would be better. I typically use || alone when the default also evaluates to false. (e.g. o.someVar || 0`)
  • That's a good point - this won't work anywhere where a false-y value is valid input, and you have to consider that when using this pattern. But more often than not, it makes sense to treat a property explicitly set to null or false in the same way as an unset property, in which case this does double duty. The warning is fair, though.
  • @Shanimal Your example is the wrong way around, it should be someVar = o.someVar === undefined ? "my default" : o.someVar;, only a minor issue but it threw me for a little bit when I first tried your code ;-)
  • yes @Metalskin we wouldn't care for the undefined value would we? lol. sorry, hopefully the mistake didn't cost you too much time :)
  • if you call console.log(emptyObj), it return {}. not { attribute1 : 'defaultValue1' }
  • Yes, because attribute1: defaultValue1 is on the prototype and console.log only enumerates items set on the top level object, not on the prototype. But, the value is there as my console.log(emptyObj.attribute1) shows.