Build Objects with Shorthand

Build Objects with Shorthand

An object literal can use a variable's name as a property key and a concise method as a function property. Shorthand reduces duplication while preserving ordinary object behavior.

Before this topic, review Build a Readable Report String if its terms are unfamiliar.

What you’ll learn

  • Explain build objects with shorthand through the school example.
  • Trace the shown operations and distinguish their result from displayed output.
  • Make the practice change and explain its consequence: Shorthand takes the edited variable value, and the method reads it from its receiver.

Work through the school example

This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.

JavaScript · school.js · complete example

const name = "Diya";
const student = { name, label() {
  return this.name;
} };
console.log(student.label());

Expected output

Diya
Run in JavaScript compiler →

What are Enhanced Object Literals?

Enhanced Object Literals were introduced in ES6 to simplify object creation syntax. They make JavaScript objects more concise, readable, and powerful.

With enhanced object literals, you can:

  • Use shorthand property names when the property name matches the variable name.
  • Define methods directly inside objects without the function keyword.
  • Use computed property names to dynamically name object keys.

1. Shorthand Property Names

If the variable name and object key are the same, you can skip the key-value syntax.

    const name = "Alice";
    const age = 28;

    const person = {
      name,
      age
    };

    console.log(person);
   { name: 'Alice', age: 28 }

Why does this work?

JavaScript assumes name: name and age: age, so the shorthand saves you from repetition.

2. Shorthand Method Definitions

You can define methods inside objects without using the function keyword.

    const calculator = {
      add(x, y) {
        return x + y;
      },
      subtract(x, y) {
        return x - y;
      }
    };

    console.log(calculator.add(10, 5));
    console.log(calculator.subtract(10, 5));
    15
    5

Question:

Can you use this method shorthand for arrow functions?

Answer: No, method shorthand only works for regular function declarations. Arrow functions are not suited for object methods because they don't have their own this.

3. Computed Property Names

You can use square brackets to define keys dynamically in objects.

    const key = "userId";
    const value = 101;

    const user = {
      [key]: value,
      name: "Bob"
    };

    console.log(user);
    { userId: 101, name: 'Bob' }

Use Case Example

Suppose you're creating a function that returns a config object with dynamic properties:

    function createConfig(option, isEnabled) {
      return {
        [option]: isEnabled,
        timestamp: Date.now(),
        log() {
          console.log(`${option} is ${isEnabled ? "enabled" : "disabled"}`);
        }
      };
    }

    const config = createConfig("darkMode", true);
    config.log();
    console.log(config);
    darkMode is enabled
    { darkMode: true, timestamp: 1683038293871, log: [Function: log] }

Key Takeaways

  • Enhanced object literals reduce redundancy and improve readability.
  • Use shorthand syntax when variable and key names match.
  • Use method shorthand for cleaner object functions.
  • Use computed properties for dynamic key generation.

Quick Recap Questions

Q: What happens if you write { x } inside an object when let x = 10?

A: It's equivalent to { x: 10 }.

Q: Can you use expressions inside computed property names?

A: Yes, for example: { [`prop${1+1}`]: "value" } results in { prop2: "value" }.

Recognize the important boundary

A method's this depends on how it is called. Extracting the method into a standalone variable can lose the expected receiver.

Try a small variation

JavaScript · original source for practice

const name = "Diya";
const student = { name, label() {
  return this.name;
} };
console.log(student.label());

Your task: Replace 'Diya' with 'Saira'. Predict the result before running the edited program.

The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.

Worked answer and reasoning

Shorthand takes the edited variable value, and the method reads it from its receiver.

JavaScript · complete worked variation

const name = "Saira";
const student = { name, label() {
  return this.name;
} };
console.log(student.label());

Expected output

Saira
Run in JavaScript compiler →

Predict the original program

JavaScript · original program for this question

const name = "Diya";
const student = { name, label() {
  return this.name;
} };
console.log(student.label());
What does the original JavaScript program display, in order?
Choose one answer. You can try again.

Answer and explanation

Diya

An object literal can use a variable's name as a property key and a concise method as a function property. Shorthand reduces duplication while preserving ordinary object behavior. A method's this depends on how it is called. Extracting the method into a standalone variable can lose the expected receiver.

Keep the useful idea

An object literal can use a variable's name as a property key and a concise method as a function property. Shorthand reduces duplication while preserving ordinary object behavior.

Check your variation against this explanation: Shorthand takes the edited variable value, and the method reads it from its receiver.

Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Create Objects with Classes →