0

In ruby we something like a.try(:property) even if a is nil(undefined) program won't throw an exception and keep going. But for nodejs/javascript if I have a.property and a is undefined program will throw an exception. I have to do something like

if (a) {
 a.property
}

It is quite tedious and unpretty.

Is there something in nodejs similar like a.try(:property) so I don't have to check before I use a property?

icn
  • 17,126
  • 39
  • 105
  • 141
  • 3
    `a && a.property`? Or `a?.property`, if you want [newer syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)? – jonrsharpe Apr 27 '20 at 16:27
  • @jonrsharpe I tried to use `a?.property` it gives `SyntaxError: Unexpected token .` for node 10 – icn Apr 27 '20 at 16:33
  • 2
    I did say "newer syntax", you need transpilation in Node: https://node.green/#ES2020-features-optional-chaining-operator----- (I thought it *was* in 14, though) – jonrsharpe Apr 27 '20 at 16:34
  • 1
    @ASDFGerte yes, I just `nvm install`'d 14 and it seems to accept e.g. `let a; a?.b` without complaining about the syntax. – jonrsharpe Apr 27 '20 at 16:41
  • @jonrsharpe Thanks a lot , I refered the link you provided :). At this moment I can use lodash _.get. it works fine. Thanks again! – icn Apr 27 '20 at 18:15

1 Answers1

-1

I dont think there's any function like that in node.js. But you could build your own utility function like this...

// utility function
let tryProp = (a, p) => ( a? (a[p] ? a[p] : null) : null);

// Testing if property exists.
let x;
x = { key: "value"};

console.log(tryProp(x, 'john')); // returns null
console.log(tryProp(x, 'key')); // returns value

// Incase variable is undefined

let y;
console.log(tryProp(y, 'key')); // returns null