JS: Object Literal Expression

By Xah Lee. Date: . Last updated: .

Object Literal Expression Syntax

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

{k1:v1, k2:v2, etc }

Return a new object with properties key k1 value v1, etc.

Property Key must be string or symbol, else, they are converted to string.

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.

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

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

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

JavaScript, Object and Inheritance