Operator ?. or the optional chaning operator allows you to check the object, its properties and methods for null and undefined, and if object or its properties/methods are defined, then access its properties or methods:
let user = null; let user2 = { name: "Alexander" }; function printName(person) { console.log(person.name); } printName(user); // Uncaught TypeError: Cannot read properties of null (reading "name") printName(user2);
We can check for null and undefined before accessing an object:
let user = null; let user2 = { name: "Alexander" }; function printName(person) { if (person !== null && person !== undefined) console.log(person.name); } printName(user); printName(user2); //Alexander
We can also shorten the check:
function printName(person) { if (person) console.log(person.name); }
operator ?. offers a more elegant solution:
let user = null; let user2 = { name: "Alexander" }; function printName(person) { console.log(person?.name); } printName(tom); //undefined printName(bob); //Alexander
The ?. operator is indicated after the name of the object. – if the value is not equal to null and undefined, then there is a call to property/method that are specified after the dot.
If the value is null/undefined, then the property/method cannot be accessed. And on the console we will see undefined.
Similarly, we can access the properties of an object using the array syntax:
let tom = { name: "Tom" }; let bob = { name: "Bob", company: { title: "Microsoft" } }; console.log(tom.company?.["title"]);// undefined console.log(bob.company?.["title"]);// Microsoft
Checking array-properties
Similarly, we can check for the existence of an array property before accessing its elements:
let tom = { name: "Tom" }; let bob = { name: "Bob", languages: ["javascript", "typescript"] }; console.log(tom.languages?.[0]); // undefined console.log(bob.languages?.[0]); // javascript
Checking Array Methods
let user = { name: "Alexander" }; let user2 = { name: "Sergey", say(words) { console.log(words); } }; console.log(user.say?.("my name is Alexander")); // undefined console.log(user2.say?.("my name is Sergey")); // my name is Bob
Check chains
let user = { name: "Alexander" }; let user2 = { name: "Bob", company: { title: "Google" } }; let user3 = { name: "Wiiliam", company: { title: "Microsoft", print() { console.log(`Company ${this.title}`) } } }; user?.company?.print?.(); // not called - no company property user2?.company?.print?.(); // not called - no print method user3?.company?.print?.(); // Company Microsoft