What is an Object Literal in JavaScript?

Learn about what JavaScript Object Literals are.

There are some concepts in programming that are named in a way that makes you think they’re more complex than they are. Object Literals are not much more complex than a list of groceries.

What is an Object Literal?

An Object is a special type of value in JavaScript that can have connections with other values.

An Object Literal is an object value that you literally write in your program/app.

An Object Literal usually consists of a list of comma-separated name-value pairs (property:value), wrapped inside curly braces {}.

Object Literal example:

const dog = {
    name: 'Naya',
    sex: 'female',
    age: 2,
    breed: 'Rottweiler mix'
};

When I say usually, I mean that an object literal could also be empty, or contain a single name-value pair:

// Empty
const dog = {}

// Single
const dog = {
    name: 'Naya'
}

In the examples above, the dog is an object value (Object Literal), which encapsulates info (data) about the dog, by using name-value pairs (e.. name: 'Naya').

So you can say that an Object Literal is a type of value (object value) in JavaScript that contains references to other values (name-value pairs).

It’s important to know that properties inside objects live inside the objects, and are scoped inside it — but values are not.

In the example above, name, sex, age, breed, are considered properties of the dog object, and they can’t be changed from the outside.

However, the values, e.g. Naya & female don’t live inside the object (they are not scoped), they are just referred to by the object properties.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi