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
.
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
.
You can use optional chaining, look at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
const foo = bar?.value
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