This content originally appeared on DEV Community and was authored by Dalibor Belic
Welcome to the first post of the Cool Syntax series! I intend to publish a post, from time to time, on how to write clean JavaScript code like a pro!
The first text is about optional chaining. A syntactic sugar that makes reading content of an object much shorter and simpler. Let me show it to you.
Take a look at this array of objects.
const art = [
{
type: "paining",
about: {
name: "The starry night",
author: "Vincent van Gogh",
year: "1889",
medium: "Oil on canvas",
},
dimensions: {
width: "92.1",
height: "73.7",
},
},
{
type: "sculpture",
about: {
name: "David",
author: "Michelangelo",
},
dimensions: {
width: "517",
height: "199",
},
},
{
type: "photography",
about: {
name: "Pillars of Creation (Eagle Nebula)",
author: "Hubble Space Telescope",
},
},
];
Imagine we fetched some data, and now we have the art
array of objects. Then, let's say we want to log type
of each object in the art
array.
art.forEach(artPiece => {
console.log(artPiece.type);
})
Now, let's log each height
.
art.forEach(artPiece => {
console.log(artPiece.dimensions.height);
})
And... Yes, it will display the error message -> TypeError: Cannot read property 'height' of undefined. It's because we don't have the dimensions
(on each object), and we're trying to get a property from it.
SOLUTION 1 - && operator
art.forEach(artPiece => {
console.log(artPiece.dimensions && artPiece.dimensions.height);
})
SOLUTION 2 - optional chaining
art.forEach(artPiece => {
console.log(artPiece?.dimensions?.height);
})
Imagine you have a complex object with many objects in objects...
w && w.x && w.x.y && w.x.y.z
vs
w?.x?.y?.z
I guess you see why optional chaining is the better solution (in terms of syntax)!
I hope you enjoyed this short syntax-related post! Check out my previous posts and stay tuned for more cool JavaScript stuff!
Cheers,
Dalibor
This content originally appeared on DEV Community and was authored by Dalibor Belic
Dalibor Belic | Sciencx (2021-05-08T10:12:36+00:00) Cool syntax #1 | Optional chaining. Retrieved from https://www.scien.cx/2021/05/08/cool-syntax-1-optional-chaining/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.