Member-only story
Javascript Optional chaining (?.)
When we access the properties of an object or call a function of a type with .
operator
We can chain with ?
so that if source is undefined or null, it will not throw an error and break the code.
Accessing object properties
const user ={ name :'Vinodh', city:'Erode' }
console.log(user.coordinates.lat); // We will end up with error
So if it is important to chain with ?
so that it will not be error when the source coordinates is undefined or null
console.log(user?.coordinates?.lat); // undefined not error
Accessing nonexistent method
let city = "erode"
city.join(); //city.join is not a function
join is an array method, but when accessing on string will result in an error
This can be rectified with ?
operator too
city.join?.()
Accessing index of undefined or null array
let cities
console.log(cities[4]) // cannot read properties of undefined
We can rectify with cities?.[4]