Python's get method for dictionaries lets me specify what should be returned if a key doesn't exist. For my current case I want a dictionary returned. How do I do this in Javascript?
-
4dict['key'] || default – ag0rex May 25 '17 at 15:56
-
There are also getters and setters in js... – Jonas Wilms May 25 '17 at 15:57
-
1Possible duplicate of [Set default value of javascript object attributes](https://stackoverflow.com/questions/6600868/set-default-value-of-javascript-object-attributes) – JJJ May 25 '17 at 16:04
6 Answers
There is no javascript equivalent of the python dictionary get method. If you would write it yourself, as a function, it would look like this:
function get(object, key, default_value) {
var result = object[key];
return (typeof result !== "undefined") ? result : default_value;
}
Use it like:
var obj = {"a": 1};
get(obj, "a", 2); // -> 1
get(obj, "b", 2); // -> 2
Note that the requested key will also be found in a prototype of obj.
If you really want a method rather than a function (obj.get("a", 2)
), you need to extend the prototype of Object. This is generally considered a bad idea though, see Extending Object.prototype JavaScript

- 472
- 3
- 10
With modern javascript you can use the nullish coalescing operator ??
const result = obj[key] ?? default;
This will return the default value if key
doesn't exist in obj
. It will also return the default in cases like {myKey: undefined}
or {myKey: null}
, which may or may not be the desired behavior.

- 9,597
- 1
- 21
- 30
JavaScript has no helper feature to do that. You need to test explicitly.
if ("myProperty" in myObject) {
return { another: "object" };
} else {
return myObject.myProperty;
}
You can use a ternary operator to do the same thing with less code.
return ("myProperty" in myObject) ? myObject.myProperty : { another: "object" };

- 914,110
- 126
- 1,211
- 1,335
-
-
@evolutionxbox — Yes. (You can use `hasOwnProperty()` if you want to exclude properties inherited from the prototype). – Quentin May 25 '17 at 16:01
-
@evolutionxbox https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in ... – Jonas Wilms May 25 '17 at 16:01
I prefer to use the logical OR like this:
foo.bar || 'default'
If checks is foo.bar is falsy, so it returns 'default' if bar is undefined.
You just need to care, that foo is an object. Otherwise a ReferenceError is thrown.

- 46
- 3
-
Stuart's answer is better. This one will return default for ANYTHING falsey. Stuart's one only does that for nully things. – Hack5 Feb 19 '22 at 08:11
You could use a proxy for this (really new ):
var handler = {
get: function(target, name){
return name in target?
target[name] :
"Default";
}
};
var dictionary={"hi":true};
var dict = new Proxy(dictionary, handler);
dict.a = 1;
dict.b = undefined;
console.log(dict.a, dict.b,dict.hi); // 1, undefined,true
console.log(dict.new); //"Default"
//the proxied object gets changed:
console.log(dictionary.a, dictionary.b,dictionary.hi); // 1, undefined,true
console.log(dictionary.new); //undefined
A proxy is an object that reflects all changes and requests trough an handler. In this case we can write/access propertys of dictionary normally, but if we access values that do not exist it'll return "Default"

- 132,000
- 20
- 149
- 151
-
For those as curious as I am: [MDN Documentation on proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy). – Jeff Noel May 25 '17 at 17:43
this works for me
let obj = {"a": 1};
let default = 100
obj["a"] || default; // -> 1
obj["b"] || default; // -> 100
But! there are some limitation, if !!obj["a"] === false
we always get default value... so it's better to just check if key in obj, to be completely sure.

- 51
- 2
- 3