How to write the equivalent of Python dictionary’s get method in JavaScript?

Sometimes, we want to write the equivalent of Python dictionary’s get method in JavaScript.

In this article, we’ll look at how to write the equivalent of Python dictionary’s get method in JavaScript.

How to write the equivalent of Python dictionary’s get method in JavaScript?

To write the equivalent of Python dictionary’s get method in JavaScript, we can use hasOwnProperty.

For instance, we write:

const obj = {
  foo: 1
}
const x = obj.hasOwnProperty("foo") ? obj.foo : "default";
const y = obj.hasOwnProperty("bar") ? obj.bar : "default";
console.log(x, y)

to call obj.hasOwnProperty with the keys we’re looking for in obj.

If hasOwnProperty returns true, that means the key is in obj.

And so we return the property’s value.

Otherwise, we return 'default'.

Therefore, x is 1 and y is default.

Conclusion

To write the equivalent of Python dictionary’s get method in JavaScript, we can use hasOwnProperty.