Javascript default options

Suppose I want to process some property of x objects in a collection array . But a collection may contain objects without such a property or even undefined . for example

let array = [
  {x: 1},
  {x: 2},
  {},
  {x: 4},
  undefined
]

The idea protects itself from such cases with a default parameter. Let it be 0 . I tried to solve it like

array.map(({x: x = 0}) => process(x))

But it does not work on undefined . Is there a way to solve this problem with default parameters and destructuring without writing the verification / set code inside the map function?

Thenks

+4
source share
2

array.map(({x : x = 0} = 0) => process(x));
+2

.filter .map, falsy , null, 0, '', false

array = array
    .filter((el) => el)
    .map(({x: x = 0}) => process(x));

Example

MDN

, undefined.

null - ., , null ,

function test(x = 10) {
    console.log(x);
}

test(undefined); // 10
test();          // 10
test(null);      // null
test(0);         // 0
test('');        // ''

Example

+1

Source: https://habr.com/ru/post/1615769/


All Articles