Skip to main content

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:

javascript
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:

TypeLiteral
Number42
String'Hello'
Array[1, 2, 3]
Object{ key: 'value' }

So an "object literal" is simply declaring an object directly via {}.


Example with methods

javascript
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:

javascript
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:

javascript
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

WayExampleNote
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
classnew User()the object is created via a class constructor

SUMMARY

PropertyObject literal
Syntax{ key: value, ... }
Copy typeCreates a new object
Can storeany data and functions
Can use variables as keysYes, via [key]
Example{ name: 'Tim', age: 25 }

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.