JSON Optional Chaining
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 24 of 65.
Optional chaining (?.) lets you safely access nested properties without worrying about errors if a property is null or undefined.
Example Without Optional Chaining:
let obj = {};
console.log(obj.key1.key2);
// Error: Cannot read properties of undefinedExample With Optional Chaining:
let obj = {};
console.log(obj.key1?.key2);
// undefined (no error)- If
key1exists, it accesseskey2. - If
key1isnullorundefined, it returnsundefinedinstead of throwing an error.
More examples:
let user = {
profile: {
name: "Alice"
}
};
console.log(user.profile?.name);
// "Alice"console.log(user.profile?.age);
// undefined (no error)console.log(user.address?.city);
// undefined (no error)This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Cheat sheet
Optional chaining (?.) safely accesses nested properties without errors if a property is null or undefined:
let obj = {};
console.log(obj.key1?.key2);
// undefined (no error)If the property exists, it accesses the next level. If it's null or undefined, it returns undefined instead of throwing an error.
let user = {
profile: {
name: "Alice"
}
};
console.log(user.profile?.name); // "Alice"
console.log(user.profile?.age); // undefined
console.log(user.address?.city); // undefinedTry it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys