JS: Object Literal Expression
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.
console.log({ aa: 7, bb: 8 }); // { aa: 7, bb: 8 }
// using string syntax for key console.log({ "aa": 7, bb: 8 }); // { aa: 7, bb: 8 }
Single Trailing Comma is Ignored
// single trailing comma is ignored // deno-fmt-ignore const x = { aa: 7, bb: 8, }; console.log(x); // { aa: 7, bb: 8 }
Repeated Comma is Syntax Error
// more than one trailing comma is error // deno-fmt-ignore const x = { aa: 7, bb: 8,, }; // error: The module's source code could not be parsed:
// cannot have repeated comma // deno-fmt-ignore const x = { aa: 7,, bb: 8 }; // error: The module's source code could not be parsed:
Key without value shorthand
(new in ECMAScript 2015)
{ a }
means
{ a: a }
if a is not defined, it's an error.
// key without value shorthand for object literal expression const aa = 3; const bb = 4; const jj = { aa, bb }; console.log(jj); // { aa: 3, bb: 4 }
Computed property key
(new in ECMAScript 2015)
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.
// object with methods const jj = { // define property as a function ff: function (x) { return x + 1; }, // arrow function syntax gg: ((x) => (x + 1)), // data property pp: 4, }; // call the function ff console.log(jj.ff(3)); // 4 // call the function gg console.log(jj.gg(3)); // 4
Method syntax shorthand
(new in ECMAScript 2015)
If the property value is a function definition by the keyword function, it has a shortcut syntax.
obj = { fname: function (args) {body} }
can be written as:
obj = { fname(args) {body} }
const jj = { ff(x) { return x + 1; }, }; console.log(jj.ff(2)); // 3
Parent of object literal expression
The parent of object created using Object Literal Expression is Object.prototype. [see JS: Prototype and Inheritance]
Property attributes
The Property Attributes of objects created by of object literal expression, is all true.
- enumerable → true
- configurable → true
- writable → true
Syntax error: unexpected token :
🛑 warning: confusing error with code block syntax.