Member-only story

Beck Moulton
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.

  1. ?. (Optional Chaining Operator): ?. allows safe navigation in chained property access, even if some properties in the chain are null or undefined, it won't throw an error. If any property in the chain doesn't exist, the value of the entire expression will be undefined.
  2. 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.

  1. !. (Non-null Assertion Operator): !. is used to assert that the result of an expression is not null or undefined. Even if TypeScript or the compiler considers it may be null or undefined, you can use !. to tell the compiler that you know it won't be null or undefined.
  2. 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…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

Responses (1)