Coolest Javascript operators you wish you would have known earlier

ยท

5 min read

Coolest Javascript operators you wish you would have known earlier

Hey Folks! hope everyone is doing great.

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 a lot of boilerplate code to do tackle them. For example, checking valid references, null/undefined handling. But recently I came across some Javascript operators which made my work a lot easier and I could write much cleaner code with their help.

Today I am going to share about those operators which 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 or not.

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 -

const user = {
  addresses: {
    /** current address is optional for a user if permanent address is same as current **/
    currentAddress: {
      contact: // some value
    },
    permanentAddress: {
      contact: // some value
    },
  }
}

Here currentAddress property can be undefined for a user, if 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 -

if (user && user.addresses && user.addresses.currentAddress) {
    const currentAddressContact = user.addresses.currentAddress.contact;
  }

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 to throw errors while accessing invalid properties.

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

/* This would evaluate to undefined if currentAddress in not present in user object */
const currentAddressContact = user?.addresses?.currentAddress?.contact;

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:

if (value === undefined || value === null) {
      return defaultValue;
} else {
     return value;
}

or

Code 2:

/* Using Nullish Coalescing Operator */
return (value ?? defaultValue);

In the above examples, both codes do the exact 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 truthy value, this would have worked pretty well to handle null checks, something like this:

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

But let me tell you guys there is a catch in using OR operator. ๐Ÿค”

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:

const currentAddressContact = user?.addresses?.currentAddress?.contact ?? "No Contact Found"

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 ReactJS, 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 as it will motivate me to write more such stuff. See you in the next post.

ย