JavaScript: Object Literal Expression
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(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}
- This is useful when you want a variable's value to be the property key.
- This syntax is necessary for property key that is Symbol.
// 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);
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
- Object Basics
- Object Overview
- Object Type
- Test If a Value is Object Type π
- Find Object's Type
- Prototype and Inheritance
- Prototype Chain
- Is in Prototype Chain?
- Get/Set Parent
- Show Parent Chain π
- Create Object
- Object Literal Expr
- Create Object + Parent
- Prevent Adding Property
- Clone Object π
- Test Object Equality π
- Add Method to Prototype