Short-circuit AND in JavaScript

Level 276 keystrokes

The && operator returns the right operand if the left is truthy, otherwise the left.

JavaScript code

// Create an object with a name property
1let user = { name: "Tom" };
// Use && for safe property access
// If user exists (truthy), access user.name
// If user were null/undefined, name would be null/undefined
2let name = user && user.name;
// Print the name value
3console.log(name);

Output

Tom
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.

  • ;× 3
  • .× 2
  • "× 2
  • &× 2
  • =× 2
  • :× 1
  • (× 1
  • )× 1
  • {× 1
  • }× 1

More JavaScript examples at level 2

← JavaScript typing practice