EN
JavaScript - optional chaining with arrays and functions
0 points
In this article, we would like to show you how to use optional chaining with arrays and functions in JavaScript.
In this example, we use optional chaining (?.
) with an array of objects to prevent errors if a reference is null
or undefined
.
xxxxxxxxxx
1
const myArray = [{ id: 1 }, { id: 2 }, { id: 3 }];
2
3
const result1 = myArray.filter((x) => x.id === 3)?.[0];
4
const result2 = myArray.filter((x) => x.id === 4)?.[0];
5
6
console.log(JSON.stringify(result1)); // {"id":3}
7
console.log(JSON.stringify(result2)); // undefined
In this example, we use optional chaining (?.
) to call a function inside the object and prevent errors if a reference is null
or undefined
.
xxxxxxxxxx
1
const myObject = {
2
myFunction: () => console.log('myFunction message'),
3
};
4
5
myObject.myFunction?.(); // 'myFunction message'
6
myObject.myFunction2?.(); // Doesn't throw error