What is the Javascript equivalent of Python's get method for dictionaries

Viewed 17100

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?

6 Answers

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.

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.

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.

Related