-1

What is a better way to write this in JS

let foo
  if(bar) foo = bar.value

I am trying to avoid react error when bar is null if i use const foo = bar.value.

Mohamed Daher
  • 339
  • 1
  • 10
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining – Dennis Vash Apr 08 '21 at 17:47
  • 1
    Does this answer your question? [Set a variable if undefined in JavaScript](https://stackoverflow.com/questions/5409641/set-a-variable-if-undefined-in-javascript) – wentjun Apr 08 '21 at 17:50
  • Also yes. I was looking for Optional chainning as answered by YohaiM – Mohamed Daher Apr 08 '21 at 19:03

2 Answers2

1

You can use optional chaining, look at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

const foo = bar?.value
YohaiM
  • 348
  • 2
  • 8
1

Try to use the chaining operator if your node version is recent enough.

const foo = bar?.value

Or the and operator to take the value of bar if bar isn't falsy.

const foo = bar && bar.value
ations
  • 91
  • 5