💻 Tech
Optional chaining allows us to check for a property or element even if it doesn’t exist without throwing an error.
In the example below, the first commented line will throw an error, indicating that the code is accessing nome
on an undefined object, which is an expected error because there are only 2 elements. You can wrap it around an if
condition like if (pessoas[3])
to check for existence, but optional chaining provides a simpler syntax to do that.
The for
loop accesses an element with complete properties, a second element with a missing property, and a non-existing element. It was able to traverse the array without errors. If the element or property doesn’t exist, the code throws undefined
instead of an error.
pessoas?.[i]?.nome
means it checks first if the ith element exists. If it exists, then it checks if the nome
property exists on the returned element. You can save a few lines of codes with this syntax.
const pessoas = [{nome: "Julia", idade: 21}, {nome: "Joao"}]
// console.log(pessoas[2].nome, pessoas[2].idade); // TypeError: Cannot read properties of undefined (reading 'nome')
for (let i = 0; i < 3; i++){
console.log(pessoas?.[i]?.nome, pessoas?.[i]?.idade);
}
// Julia 21
// Joao undefined
// undefined undefined