JavaScript
Enhanced Object Literals



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:

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);
    

Output:

    { 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));
    

Output:

    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);
    

Output:

    { 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);
    

Output:

    darkMode is enabled
    { darkMode: true, timestamp: 1683038293871, log: [Function: log] }
    

Key Takeaways

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" }.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M