TIL Optional Chaining
POSTED ON:
TAGS: javascript es2020 codepen
Very new, very ES2020.
The optional chaining
?.
is used to check if a value or a property before?.
is null or undefined .
If it is, it returnsundefined
. Otherwise, it just returns the value.
You can also use optional chaining with object methods too.
const user = {
name: "Rocky",
hairColor: "black",
};
console.log(user.age); // Can create an Error
console.log("user age?", user?.age); // undefined (no error).
console.log("user hairtype?", user?.hairColor?.hairType); // undefined (no error).
console.log("user name?", user?.name); // Rocky
See the Pen KKWGjNE by rockykev (@rockykev) on CodePen.
Related TILs
Tagged: javascript