Menu
Coddy logo textTech

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 undefined

Example With Optional Chaining:

let obj = {};
console.log(obj.key1?.key2);
// undefined (no error)
  • If key1 exists, it accesses key2.
  • If key1 is null or undefined, it returns undefined instead 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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

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);    // undefined

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow