SyntaxStudy
Sign Up
JavaScript Creating Objects with Literals
JavaScript Beginner 6 min read

Creating Objects with Literals

Creating Objects with Literals

Object literals are the most common way to create objects in JavaScript. An object is a collection of key-value pairs where keys (properties) are strings (or Symbols) and values can be any type, including other objects and functions.

Basic Object Literal Syntax

Wrap key-value pairs in curly braces. Keys can be plain identifiers, quoted strings (required for keys with spaces or hyphens), or computed expressions in square brackets.

Shorthand Properties

When a variable name matches the desired property name, you can use shorthand: instead of { name: name } write simply { name }.

Method Shorthand

Function values in an object can be written with a concise method syntax: { greet() { } } instead of { greet: function() { } }.

Computed Property Names

Square-bracket syntax allows dynamic property names at the time of object creation, which is useful for creating objects from variables or expressions.

Example
const name = 'Alice';
const age = 30;
const person = {
  name,
  age,
  'home city': 'London',
  greet() {
    return 'Hi, I am ' + this.name;
  }
};
console.log(person.name);          // Alice
console.log(person['home city']);  // London
console.log(person.greet());       // Hi, I am Alice
const key = 'score';
const game = { [key]: 100, [`${key}Max`]: 200 };
console.log(game.score);    // 100
console.log(game.scoreMax); // 200
Pro Tip

Use shorthand property names whenever a variable matches a desired key — it reduces repetition and is the idiomatic style in modern JavaScript codebases.