Optional Chaining in JavaScript

Level 4226 keystrokes

This uses optional chaining to safely access nested properties that might not exist.

JavaScript code

// User with address property
1const user1 = {
2 name: "Alice",
3 address: {
4 city: "Tokyo"
5 }
6};
7
// User without address property
8const user2 = {
9 name: "Bob"
10};
11
// ?. stops and returns undefined if the left side is null or undefined
// user1.address exists, so this prints Tokyo
12console.log(user1.address?.city);
// user2.address is undefined, so returns undefined (no error)
13console.log(user2.address?.city);
// ?.() for optional method calls
// getInfo doesn't exist, returns undefined
14console.log(user1.getInfo?.());
// ?.[] for optional array access
// hobbies doesn't exist, returns undefined
15console.log(user1.hobbies?.[0]);

Output

Tokyo
undefined
undefined
undefined
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • .× 12
  • ;× 6
  • "× 6
  • (× 5
  • )× 5
  • :× 4
  • ?× 4
  • {× 3
  • }× 3
  • =× 2

More JavaScript examples at level 4

← JavaScript typing practice