Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Object parameter destructuring, property shorthand, and method syntax

Distinguish reading properties from an argument, creating a property from a variable, and defining a method without the `function` keyword.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

function greet({ user: name = "guest", mark = "!" } = {}) { return `${name}${mark}`; }
const prefix = "Hello, ";
const obj = {
  prefix,
  greet({ user: name = "guest", mark = "!" } = {}) {
    return `${this.prefix}${name}${mark}`;
  },
};

Object destructured parameter/shorthand/method syntax groups three forms that do different jobs. In greet({ user: name = "guest", mark = "!" } = {}), the braces in the parameter list are a binding pattern, not an object literal. The method takes one argument: it reads the user property into the local parameter name and the mark property into a parameter of the same name.

The outer = {} applies only when the argument is omitted or is undefined. The inner defaults apply when a property read yields undefined, for example when the property is missing. A property value of null is kept; passing null as the entire argument throws a TypeError before the method body runs.

In an object literal, { prefix } is short for { prefix: prefix }: it creates a property named prefix with the current value of the prefix variable. Here the braces create an object rather than read properties from an argument.

The form greet(...) { ... } defines a method without a colon or the function keyword. In obj.greet(...), this is obj; extracting the method does not keep this bound to obj. Unlike greet: function (...) { ... }, the method form supports super.prop, which starts lookup at the prototype of the object where the method was defined. Calling new obj.greet() throws a TypeError. This syntax is part of ECMAScript 2024; check support in your target runtime.

Examples

const prefix = "Hello, ";
const obj = {
  prefix,
  greet({ user: name = "guest", mark = "!" } = {}) {
    return `${this.prefix}${name}${mark}`;
  },
};

console.log(obj.greet({ user: "Ada", mark: "?" }));
console.log(obj.greet());
console.log(obj.greet({ user: null }));

Result

Hello, Ada?
Hello, guest!
Hello, null!

The first call supplies both properties; the second uses both layers of defaults. In the third, `null` remains the value of `name`, and `mark` defaults to `"!"`.

Related lessons

  • JavaScript · Lesson 40 · Advanced · Version: 4

Sources