0

I know how to check whether an Object property exists.

This can complicate my code if I have several properties which may or may not be present in my Object. Python's solution is to use .get():

>>> a = {'x': 1, 'y': 2}
>>> a.get('z')
>>> a.get('z', 'hello')
'hello'

In the first case, a None (boolean-y speaking, a False) is returned.

Is there such a construction in JS (pure of tainted with a library)?

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • 1
    `a.z || 'hello'`? –  Jun 01 '17 at 12:10
  • You could use a [`Proxy`](https://stackoverflow.com/a/29723887/402037) but as always... Check the compatibility: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#Browser_compatibility – Andreas Jun 01 '17 at 12:13

1 Answers1

3

You can achieve that with a simple || operation:

var a = {x:1, y:2};

console.log(a.x); // Output: 1
console.log(a.z); // Output: undefined
console.log(a.z || 'hello'); // Output: hello

var b = (a['y'] || 'hello'); // b = 2
var c = (a['z'] || 'hello'); // c = 'hello'
rafascar
  • 343
  • 3
  • 8
  • This happens because you are trying to access the property from a variable `z`. The correct way access it would be `a['z']` or `a.z` – rafascar Jun 01 '17 at 12:49
  • 1
    This happens if one mixes up the which value is evaluated as [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) and which as [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)... :( Sorry for that... If the property you're testing has a [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) value the solution will return the "default value": [fiddle](https://jsfiddle.net/x76dxd21/) – Andreas Jun 01 '17 at 16:20