Object Destructuring Defaults in JavaScript

Level 4238 keystrokes

Object destructuring with defaults provides fallback values when properties are undefined or missing.

JavaScript code

// Destructured parameter with defaults; = {} allows calling with no argument
1function createUser({ name = "Guest", age = 18, role = "user" } = {}) {
// Return object using property shorthand
2 return { name, age, role };
3}
// Call with partial object - uses defaults for missing
4console.log(createUser({ name: "Alice" }));
// Call with no argument - uses all defaults
5console.log(createUser());
// Call with all properties - no defaults used
6console.log(createUser({ name: "Bob", age: 25, role: "admin" }));

Output

{ name: 'Alice', age: 18, role: 'user' }
{ name: 'Guest', age: 18, role: 'user' }
{ name: 'Bob', age: 25, role: 'admin' }
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.

  • "× 10
  • (× 7
  • )× 7
  • ,× 6
  • {× 6
  • }× 6
  • ;× 4
  • :× 4
  • =× 4
  • .× 3

More JavaScript examples at level 4

← JavaScript typing practice