Object Literals
Object Literals
Section titled “Object Literals”Introduction
Section titled “Introduction”Object literals use {} syntax to create objects with their properties inline. They are the most common way to create objects in JavaScript.
Syntax
Section titled “Syntax”const person = { name: 'Alice', age: 25, greet() { return `Hello, I'm ${this.name}`; }};Shorthand Properties
Section titled “Shorthand Properties”const name = 'Alice';const age = 25;
const person = { name, age };// Equivalent to: { name: name, age: age }Computed Property Names
Section titled “Computed Property Names”const key = 'dynamicField';const obj = { [key]: 'value', ['computed_' + key]: 42};// { dynamicField: 'value', computed_dynamicField: 42 }Summary
Section titled “Summary”- Object literals are
{}with property:value pairs - Use shorthand when variable name matches property name
- Use
[expression]for dynamic property names