JavaScript: Object Literal Expression

By Xah Lee. Date: . Last updated: .

The most useful and simple way to create a data 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(JSON.stringify(Object.entries(jj)) === `[["aa",7],["bb",8]]`);

Trailing Comma is Ignored

// trailing comma is ignored
const jj = { k1: 7, k2: 8 };
console.log(JSON.stringify(jj) === `{"k1":7,"k2":8}`);

Repeated Comma is Syntax Error

const jj = { a:1, , b:2};

repeated comma is error
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 xx = "cc";
const jj = { [xx]: 3 };
console.log(jj.cc === 3);
// create a key named ab, by eval an expression
const jj = { ["a" + "b"]: 4 };
console.log(jj.ab === 4);

Function as Property Value

Example of a property value that is a function.

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

// 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 jj = {
  f(x) {
    return x + 1;
  },
  g: 4,
};

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

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

JavaScript Object and Inheritance

BUY Ξ£JS JavaScript in Depth