Object literal
an object literal is the simplest and most common way to create an object in JavaScript.
It is used when you describe an object directly "in place",
using curly braces {}.
Short answer
An object literal is an expression of the form:
const user = {
name: 'Tim',
age: 25,
city: 'Kyiv'
};Here:
{}- the literal form of an object,name,age,city- the keys (properties),'Tim',25,'Kyiv'- the values.
What does "literal" mean?
A "literal" is a value written directly in the code, rather than created through a constructor or function.
For example:
| Type | Literal |
|---|---|
| Number | 42 |
| String | 'Hello' |
| Array | [1, 2, 3] |
| Object | { key: 'value' } |
So an "object literal" is simply declaring an object directly via {}.
Example with methods
const user = {
name: 'Tim',
age: 25,
sayHi() {
console.log(`Hi, ${this.name}!`);
}
};
user.sayHi(); // "Hi, Tim!"An object literal can hold not only data but also functions (methods) that work with that data.
Example with computed properties
You can use variables as keys:
const key = 'email';
const user = {
name: 'Tim',
[key]: 'tim@mail.com'
};
console.log(user.email); // "tim@mail.com"The [] brackets let you set a dynamic property name when the object is created.
Shorthand notation (ES6+)
If the variable name matches the key, you can write it more concisely:
const name = 'Tim';
const age = 25;
const user = { name, age };
console.log(user); // { name: 'Tim', age: 25 }Here name: name automatically shortens to just name.
Comparison with other approaches
| Way | Example | Note |
|---|---|---|
| Object literal | { name: 'Tim' } | the simplest and most popular |
new Object() | const obj = new Object(); | more verbose syntax |
Object.create(proto) | Object.create(null) | used to control the prototype |
class | new User() | the object is created via a class constructor |
SUMMARY
| Property | Object literal |
|---|---|
| Syntax | { key: value, ... } |
| Copy type | Creates a new object |
| Can store | any data and functions |
| Can use variables as keys | Yes, via [key] |
| Example | { name: 'Tim', age: 25 } |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.