r/node • • Nov 10 '20

Conditionally call a function with optional chaining.

Post image
345 Upvotes

126 comments sorted by

View all comments

1

u/FunkyFreshFarming Nov 10 '20

Can someone help ELI5 for a jr developer?

4

u/wobsoriano Nov 10 '20

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

The optional chaining ‘?.’ is an error-proof way to access nested object properties, even if an intermediate property doesn’t exist.

const user = {};

// error: Uncaught TypeError: Cannot read property 'first' of undefined
console.log(user.name.first)

// ok, but returns undefined
console.log(user?.name?.first)

2

u/FunkyFreshFarming Nov 10 '20

Okay that helps me understand how it works, thank you for the link. I still don't understand why we would want to use this however.

2

u/KyleG Nov 10 '20

It's a hacky way, with a dynamically-typed language, to write terser code with potential null values. It doesn't really solve the problem of programmers forgetting to check for nullity, since there's nothing stopping a programmer from forgetting to use ? there.

1

u/TheMetalFleece Nov 10 '20

Yep. This is why I always enable "strictNullChecks" (or "strict" in general) on every typescript project. You get an "object may be undefined" error and it doesn't compile.

1

u/donner9 Nov 10 '20

interesting... is it just for typescript, right?

1

u/TheMetalFleece Nov 10 '20

Yeah. You can see more info here (along with other "strict" checks). I'ts game-changing https://www.typescriptlang.org/tsconfig#strictNullChecks

1

u/noXi0uz Nov 10 '20

there is though. Typescript and your IDE will show an error that the value you are trying to access may be undefined, forcing you to either use optional chaining or another form of null check

1

u/Not_Sugden Nov 10 '20

its mainly just clearer for specific use cases, but idk i dont find it all that useful, i've only used it like once