0

Im trying to set a default value to an array inside an object but for some reason it keeps the null value. What am i doing wrong and how can i set the default value ?

var response = {
  suggestions: null
}

const {
  suggestions = [],
} = response || {}

console.log(suggestions)
Emile Bergeron
  • 16,148
  • 4
  • 74
  • 121

2 Answers2

0

A default value is only applied if a property is undefined, not null.

If you want to provide a default value even in case of null, you can use nullish operators instead of unpacking.

const suggestions = response?.suggestions ?? [];
// defaults to [] if response or response.suggestions is null or undefined
Domino
  • 5,681
  • 32
  • 55
0

Default values only work with undefined, if you want it to fall through to a default, set your value in your object to undefined instead of null

var response = {
  suggestions: undefined
}

const {suggestions = [],} = response ||{}
console.log(suggestions)
mhodges
  • 10,480
  • 2
  • 25
  • 45