Skip to content

Object Literals

This lesson explains Object Literals with clear examples, use cases, and best practices so you can use modern JavaScript confidently in real projects.

ES6+ Object Literals Overview

ES6 enhanced object literal syntax with shorthand properties, shorthand methods, and computed property names. These improvements make object creation shorter, cleaner, and more expressive in modern JavaScript.

Object literals are one of the most common ways to create structured data in JavaScript. They are used for API payloads, configuration objects, React props, state updates, and utility return values.

Feature Description
Introduced In ES6 (ECMAScript 2015)
Shorthand Properties { name } instead of { name: name }
Shorthand Methods method() { ... } inside objects
Computed Properties [expression]: value
Common Uses Config objects, API data, state, utilities
Works With Destructuring, spread, classes, modules

Basic Object Literal Example

const name = "Alex";
const role = "admin";

const user = {
  name,
  role,
  isActive: true
};

console.log(user);

When the property name and variable name are the same, ES6 lets you write the property once using shorthand syntax.

How ES6 Object Literals Work

ES6 object literal enhancements reduce repetition by letting JavaScript infer property names, define methods more cleanly, and use dynamic keys at creation time.

Step Description Example
Create Variables Prepare values you want in the object. const title = "Book"
Use Shorthand Write property name once. { title }
Add Methods Define functions directly in the object. show() { ... }
Use Dynamic Keys Compute property names with expressions. [key]: value
Return or Use Pass object to functions or APIs. return user

Property Shorthand

const id = 101;
const title = "Modern JavaScript";
const price = 29;

// ES5 style

const oldProduct = {
  id: id,
  title: title,
  price: price
};

// ES6 shorthand

const newProduct = {
  id,
  title,
  price
};

console.log(oldProduct);
console.log(newProduct);

Shorthand properties are especially useful when building objects from function parameters or local variables.

Shorthand in Function Returns

function createUser(
  name,
  email,
  role
) {
  return {
    name,
    email,
    role,
    createdAt: new Date().toISOString()
  };
}

const user =
  createUser(
    "Sam",
    "sam@example.com",
    "editor"
  );

console.log(user);

Returning object literals with shorthand syntax keeps factory functions and API helpers concise.

Method Shorthand

const calculator = {
  value: 0,

  add(num) {
    this.value += num;
    return this;
  },

  subtract(num) {
    this.value -= num;
    return this;
  },

  getResult() {
    return this.value;
  }
};

calculator
  .add(10)
  .subtract(3);

console.log(
  calculator.getResult()
);

ES6 method shorthand removes the need for methodName: function() syntax inside object literals.

Computed Property Names

const field = "email";
const prefix = "user";

const profile = {
  [`${prefix}Id`]: 42,
  [field]: "alex@example.com",
  ["is" + "Active"]: true
};

console.log(profile);

Computed property names let you use expressions inside square brackets to define dynamic keys at object creation time.

Dynamic Keys from Variables

function buildFilter(
  key,
  value
) {
  return {
    [key]: value
  };
}

const themeFilter =
  buildFilter("theme", "dark");

const roleFilter =
  buildFilter("role", "admin");

console.log(themeFilter);
console.log(roleFilter);

This pattern is common in search filters, form state builders, and reducers where property names are not known in advance.

Combining All ES6 Object Literal Features

function createCounter(label) {
  let count = 0;

  return {
    label,
    increment() {
      count += 1;
      return count;
    },
    reset() {
      count = 0;
    },
    [`${label}Count`]: () => count
  };
}

const views =
  createCounter("views");

console.log(views.increment());
console.log(views.viewsCount());

Real-world objects often combine shorthand properties, shorthand methods, and computed keys in the same literal.

Object Literals with Spread

const defaults = {
  theme: "light",
  language: "en"
};

const userPrefs = {
  language: "fr"
};

const settings = {
  ...defaults,
  ...userPrefs,
  notifications: true
};

console.log(settings);

Object literals work well with the spread operator for merging defaults and overrides into a new object.

ES5 vs ES6 Object Literal Syntax

Feature ES5 Syntax ES6 Syntax
Property { name: name } { name }
Method greet: function() { ... } greet() { ... }
Dynamic Key Create object first, then assign { [key]: value }
Readability More verbose Shorter and clearer

Common Object Literal Use Cases

  • Building API request and response payloads.
  • Returning structured data from utility functions.
  • Creating configuration and settings objects.
  • Defining simple service objects with methods.
  • Building dynamic form or filter state.
  • Creating React component props and state objects.
  • Mapping variables into objects for logging or debugging.

Object Literal Best Practices

  • Use shorthand properties when variable and key names match.
  • Prefer method shorthand for object methods in modern code.
  • Use computed keys when property names are dynamic.
  • Keep object literals focused and readable.
  • Combine with spread for immutable updates when needed.
  • Use clear property names instead of overly clever expressions.
  • Avoid mixing too many dynamic keys in one literal.

Common Object Literal Mistakes

  • Using shorthand when the property name should differ from the variable.
  • Forgetting square brackets for computed property names.
  • Confusing method shorthand with arrow functions inside objects.
  • Assuming shorthand works for renamed properties automatically.
  • Creating overly nested literals that are hard to maintain.
  • Mutating shared objects instead of creating new ones when needed.
  • Using dynamic keys when a static key would be clearer.

Key Takeaways

  • ES6 object literals support shorthand properties and methods.
  • Computed property names allow dynamic keys with [expression].
  • These features reduce repetition and improve readability.
  • Object literals are widely used in modern JavaScript apps.
  • They work naturally with destructuring, spread, and modules.

Pro Tip

When returning objects from functions, use shorthand properties for matching variable names and method shorthand for object behavior. This keeps factory functions clean and easy to scan.