Member-only story
2 min readApr 21, 2024
Understanding `?.` and `!.` Operators in JavaScript
In JavaScript, ?.
and !.
are two different operators used for accessing object properties and invoking methods.
?.
(Optional Chaining Operator):?.
allows safe navigation in chained property access, even if some properties in the chain arenull
orundefined
, it won't throw an error. If any property in the chain doesn't exist, the value of the entire expression will beundefined
.- For example:
let obj = {
foo: {
bar: {
baz: 42
}
}
};
console.log(obj?.foo?.bar?.baz); // Outputs 42
console.log(obj?.foo?.qux?.baz); // Outputs undefined
console.log(obj?.nonExistent?.property); // Outputs undefined
In the above example, ?.
allows us to safely navigate through the properties of the obj
object, even if some properties don't exist.
!.
(Non-null Assertion Operator):!.
is used to assert that the result of an expression is notnull
orundefined
. Even if TypeScript or the compiler considers it may benull
orundefined
, you can use!.
to tell the compiler that you know it won't benull
orundefined
.- For example:
let obj = {
foo: {
bar: {
baz: 42
}
}
};
console.log(obj!.foo!.bar!.baz); // Outputs 42
console.log(obj!.nonExistent!.property); // Throws TypeError: Cannot read property 'property' of undefined
In the above example, !.
informs the compiler that we are sure the properties and methods of the obj
object exist. If they don't exist, it will throw an…