DEV Community

loading...
Cover image for Optional Chaining in javascript.

Optional Chaining in javascript.

lakshaykalra profile image Lakshay Kalra ・2 min read

Imagine we have a deeply nested object of level "N" and we want to check the "Mth" level if it exists or not. Let me put an example in front of you.

Let customer={
name:'Foo',
cars:{
carOne:'Audi',
carTwo:'BMW'
 }
}
Enter fullscreen mode Exit fullscreen mode

If I have to say lets check "carOne" property is present or not in customer object, I can do this,

if(customer && customer.cars && customer.cars.carOne) {
// do your stuff
}
Enter fullscreen mode Exit fullscreen mode

It's easy, right?

But if we observe the code above carefully, What we have found?

  • Duplicate Code - To check a property exists or not, we are re-writing some conditions of the code again and again. Means some part of the code is executing many times. Thereby increasing code execution time.
  • Longer version - If we are writing multiple conditions to check for a property, The code becomes lengthy and if we skip some validation in between, we can get an error.

let customer={
  name:'Foo',
  }

  if(customer  && customer.cars.carOne) { // will result in TypeError:Cannot read property 'carOne' of undefined
    // do your stuff
    }
Enter fullscreen mode Exit fullscreen mode

How about we fix this guy into a one-liner statement. And here's the code for your rescue.

if( customer?.cars?.carOne ) {
// do your stuff
}

Enter fullscreen mode Exit fullscreen mode

Boom!! All your problems just got vanished.

Here's How.

The expression "?." is called Optional Chaining and it's evaluating whether an expression before the "?" statement is Nullable and/or Undefined. If it is, The whole expression will stop executing, or in a technical term, it's called "Short-Circuiting" and the code execution will just be carried on afterward.

Benefits?

  • No Duplicate code - The optional chaining expression is not checking the same condition again and again if it's already been examined. Here's, Kind of continuous chaining is happening. So no object property will be traversed multiple times. Thereby, Saving code execution time.

  • Shorter and simplified version - This is of course shorter and easy to read, unlike the vanilla code. As optional chaining is also checking Nullable and/or Undefined throughout the way, it will not result in "TypeError". In this case, execution still continues.

I hope you find this blog interesting. Until next time, Adios amigos.

Discussion (7)

pic
Editor guide
Collapse
yellow1912 profile image
yellow1912

Thank you. I learned something new today. Can we do that with dynamic property?

Collapse
lakshaykalra profile image
Lakshay Kalra Author

Awesome, this is my first blog and I'm glad this helped you to learn something.

About dynamic property, yes you can do that. As object is already created no matter where the properties of it came from.

Collapse
janpauldahlke profile image
jan paul

Best new feature. I instantly applied it to my recent project.

Collapse
lakshaykalra profile image
Lakshay Kalra Author

Yeah it is. We learn and implement. Best practice ever 🙂

Collapse
amitavmishra99 profile image
Amitav Mishra

Just to add (?.) is also called Elvis operator. Anyway great content. One quick suggestion - add syntax highlighting using markdown.
github.com/adam-p/markdown-here/wi...

Collapse
lakshaykalra profile image
Lakshay Kalra Author

Correct me if I'm wrong, I think elvis operator is "? :" Which is also called ternary operator in JS.

Check out this link.

en.m.wikipedia.org/wiki/Elvis_oper...

Collapse
amitavmishra99 profile image
Amitav Mishra

Well some links say "?:" is elvis operator and some says "?."
After few research I found Elvis operator is "?:" and "?." is actually Safe Navigation operator. Thanks for reminding :)

Link that says "?." is elvis operator ->
joshmorony.com/safely-displaying-d...

Some stackoverflow discussion ->
stackoverflow.com/questions/440469...