JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Cool JavaScript Operators You Should Know

--

I code a lot in JavaScript, be it at work or for my personal projects. I usually came across situations where I have to write many boilerplate codes to tackle them. For example, checking valid references, null/undefined handling. But recently came across some JavaScript operators who made my work a lot easier, and I could write much cleaner code with their help.

Today I will share about those operators that I believe you could also use to write better code.

Optional Chaining Operator (?.)

If you would have been using JavaScript for quite a while, then you might have faced this irritating error Cannot read property '<property-name>' of undefined. This issue is generally faced when you try to access a property located deep in an object by creating chains like a.b.c..... and you forgot to check if an intermediate value in the chain exists.

Let’s understand it with a proper example.

Consider a user object, which can have different properties of a user like his addresses and contact information. The user object can look like as below -

user object structure

Here, currentAddress property can be undefined for a user, if the user currently lives in the permanentAddress.

Since the user object is flexible; we have to add manual checks to access the contact information in currentAddress to avoid undefined reference errors as below -

Traditional method to check for reference errors

Now, this is a lot of code to access a value inside an object. Imagine the amount of boilerplate code you would have to write if any property is located very deep inside an object.

That’s where the optional chaining operator (?.) comes to the rescue.

As per MDN (Mozilla Developer Network) docs: “The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.”

In simple terms, if you use the optional chaining(?.) operator, JavaScript knows that it first has to check for the chain user.addresses.currentAddress to be valid. If it finds that valid, it returns the property value; else returns undefined.

Optional chaining operator (?.) does short-circuiting. It means that JavaScript stops evaluating properties in the chain once it finds an invalid/non-existent value. For example: in user.addresses.currentAddress.contact, if currentAddress was not present, then JavaScript will not evaluate contact value thereafter and will return undefined as an output. This behavior prevents JS from throwing errors while accessing invalid properties.

So, we can now directly get contact information without adding too much boilerplate code.

Accessing properties using optional chaining

Not only this, but you can also use it for the following :

  • access array items,
  • make function calls
  • access expressions
obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)

Isn’t it really cool operator? Let’s head to another cool operator in JavaScript.

Nullish coalescing operator (??)

Are you too sick of writing conditional statements for handling null/undefined checks?

What if you have an operator to reduce the boilerplate code? To understand its use case better, let’s take examples:

Code 1:

Traditional method of Null/Undefined handling

Code 2:

Using Nullish Coalescing Operator

In the above examples, both codes do the same thing. They return a default value when the value is null/undefined; else value itself. As you will notice, using code 2 is much cleaner and cuts a lot of boilerplate. That's where the power of Nullish Coalescing Operator (??) comes into the picture.

As per MDN docs: “The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.”

Some of you might argue here that we could have used the logical OR operator (||) instead. Since OR ( || ) operator returns the first value, this would have worked pretty well to handle null checks, something like this:

/* Using OR operator instead */
return (value || defaultValue);

There is a catch in using OR operator, however.

The OR operator returns the right-hand side value if the left-hand side value is falsy, not just null/undefined. There are six values in JavaScript which are considered as falsy. These are the following:

  • undefined
  • null
  • ""(empty string)
  • NaN
  • 0
  • false

So if you would use an OR operator, it will return the default value even in the case when the value is not just null/undefined. This is not what we wanted. We just wanted to return default when our value is null or undefined.

The nullish coalescing operator avoids this pitfall by only returning the second operand when the first one evaluates to either null or undefined (but no other falsy values).

TIP: You can use Optional Chaining and Nullish Coalescing operators together to return a default value when some property is not present deep in an object. For example:

Using Optional Chaining and Nullish Coalescing Operator Parallely

Key Takeaways

  • When you need to access a property deep in an object, you can use Optional Chaining operator (?.) to avoid errors due to invalid chains.
  • When you need to handle null/undefined checks, you can use Nullish Coalescing Operator (??) to avoid writing unnecessary conditional checks.

About Me

I am a Software Engineer by profession. I like to work on frontend technologies like React, TypeScript. I am new to blogging and like to share my learnings with the community. I hope you will like my first blog.

If you like the content, do share it to motivate me to write more such stuff. See you in the next post.

Originally published at https://codeslayer.hashnode.dev.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Written by Utkarsh Garg

Sharing things as I learn with the community. Software Engineer. Curious cat.

Responses (2)

Write a response