JavaScript Optional Chaining Proposal #10daysUnknownJSChallenge #day7

JavaScript Optional Chaining proposal came to solve the major problem that every JavaScript developer facing during object property access. Most useful while accessing nested object property

const user = {
	name: 'Hendry',
	age: 23,
	address: {
		state: 'San Jose',
		country: 'USA'
	}
}

// Typical way of safe property accessing
const state = user.address && user.address.state

The above syntax is fine and quite readable while accessing the property at one level. Consider having to access the nested level property, we have to use more logical and (&&) operator and the code will become less readable and even it may lead to error-prone

The Optional Chaining

Proposal: https://github.com/tc39/proposal-optional-chaining

The optional chaining operator allows developers accessing object property while keeping the code more readable and understandable.

// Accessing obeject property using optional chaining method
const obj = { 
	foo: { 
		bar: { 
			baz: 42 
		}
	}
};

const baz = obj?.foo?.bar?.baz; // 42
const unknown = obj?.foo?.bar?.buzz; // undefined

Optional Chaining Usage

Optional chaining can be used in the following three positions.

obj?.prop       // optional static property access
obj?.[expr]     // optional dynamic property access
func?.(...args) // optional function or method call

Static and dynamic property access is straight forward. Let's look at the function/method call with optional chaining

  
a?.b() 
// undefined if `a` is null/undefined
// throws a TypeError if `a.b` is not a function
// otherwise, evaluates to `a.b()`

a?.()
// undefined if `a` is null/undefined
// throws a TypeError if `a` is neither null/undefined, nor a function
// invokes the function `a` otherwise

// We can also pass the arguments like a typical function call

There are three important thing needs to know furthermore about optional chaining

Short-circuiting

If the expression on the LHS of ?. evaluates to null/undefined, the RHS is not evaluated. This concept is called short-circuiting.

transaction?.success?.[++orderCount]

orderCount value will be increased only if transaction?.success? is not null/undefined

Stacking

An Optional Chain may be followed by another Optional Chain.

a?.b?.c

Optional deletion

Delete an object property if it is not null or undefined

delete a?.b

Using with Babel

The proposal will be added to the next soonest practical release of the JavaScript. Currently Chrome 80, Firefox 74 & Opera 67 supports the proposal. To use with backward compatibility consider using the following Babel plugin

https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining