1

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
  • 17,074
  • 5
  • 83
  • 129
Tiago Palmas
  • 113
  • 2
  • 7

2 Answers2

1

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
  • 6,314
  • 1
  • 32
  • 58
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,938
  • 2
  • 28
  • 46