Object literal
- Node.js course
- Beginner
- Lesson 65/116
- 4 min
Learn to create objects with {}.
Object literal
An object groups related data under a single value. The simplest form is the object literal: key-value pairs inside curly braces.
The syntax is { key: value }. In each pair key is the property name and value is the value assigned to it. Multiple pairs are separated by commas. Example: { name: 'Ayşe', age: 30 } is an object with two properties.
Property names are usually strings; values can be anything: numbers, strings, arrays, even other objects. This flexibility makes objects a powerful tool for modelling data.
Property and value
Each pair inside an object is called a property. The left side is the name, the right side is the value. The value can change later; the name stays fixed after the object is created.
Even if you declare the object with const, its property values can still change. const only fixes the variable binding; it does not freeze the object. Example: const user = { name: 'Ayşe' }; user.name = 'Mara'; is valid.
A property name can also be a number, boolean, or variable; JavaScript converts it to a string automatically. So { 1: 'a' } and { '1': 'a' } are the same object.
Practice Print a user object
Define a user object with name set to 'Ayşe' and age set to 30. Print the name property with console.log.
Starter code
// Define the user object and print its name propertySample solution
const user = { name: 'Ayşe', age: 30 };
console.log(user.name);Expected output
Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which object literal is valid?
- { 'name': 'Ayşe' } Correct answer
- { name: 'Ayşe' }
- { name = 'Ayşe' }
- { name -> 'Ayşe' }
Explanation: quoting the key is also valid; the separator is a colon.
2 User object
const user = { name: ____, age: 28 };
const user = { name: 'Ayşe', age: 28 };
Explanation: string values go inside quotes.
3 Match the object parts
| Term | Meaning |
|---|---|
{ } |
Object start and end |
name |
Property name |
'Ayşe' |
Property value |
: |
Name-value separator |