JavaScript: Object Literal Expression
The most useful and simple way to create a object is using the literal expression {β¦}
.
{k1:v1, k2:v2 etc}
- Return a new object with properties key k1 value v1, etc.
// create object with 2 properties const jj = {aa:7, bb:8}; console.log( jj ); // { aa: 7, bb: 8}
Property key must be string or symbol, else, it's converted to string automatically. [see Property Key]
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 not ok const hh = { a:1, , b:2}; // SyntaxError: Unexpected token
Function as Property
Example of a property value that is a function:
// example of object with a method const my = { dd:7, ff: function (x) { return x + 1; }, }; console.log( my ); // { dd: 7, ff: [Function: ff] } // call the function console.log( my.ff(3) ); // 4
Computed Property Key (JS2015)
If property key is enclosed by square bracket [key]
, the key is evaluated as expression.
obj = {[expression]:value}
// es2015 computed property syntax. use [] around the property key const obj = {["a" + "b"]: 4 }; console.log(obj.ab); // 4
This is useful when you want a variable's value to be the property key.
// computed property key const x = "cc"; const obj = {[x]: 3}; console.log(obj.cc); // 3
This new syntax is especially useful for property key that is symbol. [see Symbol Tutorial]
Method Syntax Shorthand (JS2015)
obj = { fname() {body} }
is equivalent to:
obj = { fname: function () {body} }
// new syntax shorthand for method, ES2015 const obj = { f(x) { return x + 1; }, g:4 }; console.log( obj.f(2) === 3); // true
Parent of {}
The parent of object created using Object Literal Expression is Object.prototype. [see Prototype and Inheritance]
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 Object.create]
// check equivalence of 2 ways to create a object const o1 = {"p":1}; const o2 = Object.create( Object.prototype, { "p": {value:1, enumerable: true, configurable: true, writable: true} } ); console.log( Reflect.getPrototypeOf(o1) === Reflect.getPrototypeOf(o2) ); console.log( Object.isExtensible ( o1 ) ); console.log( Object.isExtensible ( o2 ) ); console.log( JSON.stringify ( Object.getOwnPropertyDescriptor(o1, "p") ) === JSON.stringify ( Object.getOwnPropertyDescriptor(o2, "p") ) ); // all true