JS: 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 …} → returns a new object with properties key k1 value v1, etc.

// create object with 2 properties
var o2 = {"aa":7, "bb":8};
console.log( o2 ); // { aa: 7, bb: 8}
// property key is converted to string if not string
var o2 = {aa:7};
console.log( o2 ); // { aa: 7}
// property key can only be type string or type symbol (ES6)

Object Literal Expression vs Object.Create

{k1:v1 …}

is equivalent to

Object.create(Object.prototype,{k1:{value:v1, enumerable: true, configurable: true, writable: true},…})

[see JS: Object.create]

// check equivalence of 2 ways to create a object

var o1 = {"p":1};

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

console.log( Object.getPrototypeOf(o1) === Object.getPrototypeOf(o2) ); // true

console.log( Object.getOwnPropertyDescriptor(o1, "p") );
// { value: 1, writable: true, enumerable: true, configurable: true }

console.log( Object.getOwnPropertyDescriptor(o2, "p") );
// { value: 1, writable: true, enumerable: true, configurable: true }

console.log ( Object.isExtensible ( o1 ) ); // true
console.log ( Object.isExtensible ( o2 ) ); // true

Prototype of Object Literal Expression

The parent of object created using {…} is Object.prototype.

[see JS: Prototype and Inheritance]

[see JS: Object.prototype]

Object Literal Expression Extensions

[see JS: ES2015 Object Literal Expression Extensions]

Object and Inheritance Topic

  1. JS: Object System Overview
  2. JS: What's Object?
  3. JS: Prototype and Inheritance
  4. JS: Create Object
  5. JS: Object Literal Expression
  6. JS: Find Object's Prototype
  7. JS: Set Object's Prototype
  8. JS: How to Create Object with Parent X?
  9. JS: Prevent Adding Property
  10. JS: Determine Type of Object
  11. JS: Primitive Value Object Wrapper
  12. JS: Clone, Deep Copy Object/Array
  13. JS: Test Equality of Objects

  1. JS: Object Object
  2. JS: Object.prototype
Liket it? Put $1 at patreon.

Or, Buy JavaScript in Depth