JavaScript: Object Literal Expression

By Xah Lee. Date: . Last updated: .

The most useful and simple way to create a object is using the literal expression.

{k1:v1, k2:v2 }
Return a new object with properties key k1 value v1, etc.
Property Key must be string or symbol, else, it's converted to string automatically.
const jj = {aa:7, bb:8};

console.log( jj ); // { aa: 7, bb: 8}

Ending Comma Ok

// ending comma is ok
const h4 = { k1:7, k2:8, };

console.log( h4 ); // { k1: 7, k2: 8 }

Repeated Comma is Syntax Error

// repeated comma is error
const hh = { a:1, , b:2};
// SyntaxError: Unexpected token

Computed Property Key (JS2015)

If property key is enclosed by square bracket [key], the key is evaluated as expression.

obj = {[expression]:value}

// object literal expression, with a computed key name from a variable
const x = "cc";
const obj = { [x]: 3 };
console.log(obj.cc === 3);
// create a key named ab, by eval an expression
const obj = { ["a" + "b"]: 4 };
console.log(obj.ab === 4);

Function as Property Value

Example of a property value that is a function.

// example of object with a method
const x1 = {
  dd: 7,
  ff: ((x) => (x + 1)),
};

console.log(x1); // { dd: 7, ff: [Function: ff] }

// call the function
console.log(x1.ff(3) === 4);

Method Syntax Shorthand (JS2015)

If the property value is a function definition by the keyword function, it has a shortcut syntax.

obj = { fname: function () {body} }

can be written as:

obj = { fname() {body} }

const obj = {
  f(x) {
    return x + 1;
  },
  g: 4,
};

console.log(obj.f(2) === 3);

TIP: best to use Arrow Function

Parent of {}

The parent of object created using Object Literal Expression is Object.prototype. [see Prototype and Inheritance]

Object Literal Expression vs Object.Create

{key:val}

is equivalent to

Object.create( Object.prototype, {key: {value:val, enumerable: true, configurable: true, writable: true}})

[see Object.create]

// check equivalence of 2 ways to create a object

const x1 = { "p": 1 };

const x2 = Object.create(
  Object.prototype,
  { "p": { value: 1, enumerable: true, configurable: true, writable: true } },
);

console.log(Reflect.getPrototypeOf(x1) === Reflect.getPrototypeOf(x2));

console.log(Object.isExtensible(x1));
console.log(Object.isExtensible(x2));

console.log(
  JSON.stringify(Object.getOwnPropertyDescriptor(x1, "p")) ===
    JSON.stringify(Object.getOwnPropertyDescriptor(x2, "p"))
);

// all true

JavaScript Object and Inheritance

BUY
Ξ£JS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc