2

I was wondering if it is possible to override "undefined" for uninitiated keys of an object such that:

var obj={} console.log(obj.randomKey) output in console: 0 

I am well aware that I "forgot" to initate obj.randomKey. That is in fact my question.

Can I have a default value for any uninitiated key of an object or a class?

If you are curious

The reason I am asking is that I am trying to solve a riddle that allows creation of object with "native" language such as:

const jane = new Thing('Jane') jane.name // => 'Jane' // can define boolean methods on an instance jane.is_a.person jane.is_a.woman jane.is_not_a.man jane.is_a_person // => true jane.is_a_man // => false 

And this is the first strategy I am taking :)

Update: I solved the riddle :) If anyone's interested in trying: https://www.codewars.com/kata/the-builder-of-things/train/javascript

1
  • 1
    You might find Proxy useful. Commented May 10, 2017 at 9:20

2 Answers 2

5

You can't really define a default value, but you can use ES2015 proxies to pretend that they have one:

function createObj(obj) { return new Proxy(obj, { get(target, key, receiver) { if (target[key] === undefined) { return 0; } return Reflect.get(target, key, receiver); } }); } const myObj = createObj({}); console.log(myObj.test); // 0 

Nice approach to a language btw!

Sign up to request clarification or add additional context in comments.

1 Comment

AWESOME! Exactly what I was after!
1

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"; 

1 Comment

o.someVar || "my default" produce wrong result when someVar prop has falsy value (e.g. 0, false, ..)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.