liveBook · Manning

Object literal

As explained in The Joy of JavaScript

A JavaScript syntax form for creating an object directly from a literal expression.

An object literal creates an object directly from a literal expression. It is usually the quickest choice for a one-time object or for grouping related data passed to or returned from a function. section 1.2

Choose an object-creation approach according to how the objects will be used:

  • Use an object literal for a single object or a small data bundle. section 1.2
  • Use Object.create, a factory function, or a class when multiple objects share a shape or prototype relationship. section 1.2
  • Use the spread operator or Object.assign to combine several objects into a new object. section 1.2

A literal used as a prototype

const transaction = { sender: 'luis@tjoj.com', recipient: 'luke@tjoj.com' }; const moneyTransaction = Object.create(transaction); moneyTransaction.funds = 0.0; moneyTransaction.addFunds = function addFunds(funds = 0) { this.funds += Number(funds); }; moneyTransaction.addFunds(10.0); // moneyTransaction.sender === 'luis@tjoj.com' // moneyTransaction.funds === 10 section 2.1

Listing 2.2 Transaction objects linked by a basic prototype setup
const transaction = {                                           #1
   sender: 'luis@tjoj.com',
   recipient: 'luke@tjoj.com'
};
 
const moneyTransaction = Object.create(transaction);            #2
moneyTransaction.funds = 0.0;
moneyTransaction.addFunds = function addFunds(funds = 0) {      #3
  this.funds += Number(funds);
}
 
moneyTransaction.addFunds(10.0);
moneyTransaction.funds; // 10.0

Inspect the complete transaction example, including the literal’s properties, the Object.create relationship, and the added method. section 2.1

How The Joy of JavaScript covers it

How deep it goes
Defines direct creation and contrasts alternatives, then shows a literal serving as a prototype without developing property descriptors.
Examples
Uses a transaction literal containing sender and recipient data, then links a money transaction to it with Object.create.
What it assumes
Assumes familiarity with JavaScript objects and references while establishing object literals as a direct creation form.
What you can do after
Apply it to create compact one-off data objects and prototype objects, while selecting factories or classes for repeated shapes.
How it connects
Connects object literals to Object.create, prototypes, object factories, classes, the spread operator, and Object.assign.

Also explained in

Compare how 2 books explain object literal →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.