Back to JavaScript
2026-05-056 min read

object literal (JavaScript)

Learn object literal (JavaScript) step by step with clear examples and exercises.

Title: Mastering Object Literals in JavaScript: A full guide

Why This Matters

Object literals are a fundamental concept in JavaScript, enabling developers to create and manipulate complex data structures. They're essential for working with real-world applications, interviews, and debugging common issues. Understanding object literals will empower you to build more robust and scalable JavaScript projects.

The Importance of Object Literals

  1. Organizing Data: Objects help keep related data together, making your code easier to read and maintain.
  2. Functionality: Object properties can be functions, allowing for the creation of reusable code.
  3. Flexibility: Objects can store different types of data, including primitive values, arrays, and even other objects.
  4. Encapsulation: By grouping related variables and functions within an object, you can achieve encapsulation, which helps to minimize the impact of changes on your code.
  5. Prototypal Inheritance: Objects in JavaScript follow a prototypal inheritance model, allowing for efficient code reuse and dynamic object creation.

Prerequisites

To get the most out of this lesson, you should have a solid understanding of the following:

  1. Variables and data types in JavaScript
  2. Basic JavaScript syntax, including operators and expressions
  3. Functions and control structures (if-else, for, while)
  4. Understanding the concept of scope in JavaScript
  5. Familiarity with arrays and their properties and methods
  6. Understanding prototypes and the prototype property
  7. Basic understanding of the event loop and asynchronous JavaScript

Core Concept

Definition and Syntax

An object literal is a comma-delimited list of zero or more pairs of property names and associated values enclosed in curly braces {}. Properties consist of a key (name) and a value. The keys are strings, while the values can be any JavaScript data type.

const myObject = {
name: 'John Doe',
age: 30,
isStudent: false,
hobbies: ['reading', 'gaming'],
};

Accessing Object Properties

You can access object properties using the dot notation (.) or bracket notation ([]).

console.log(myObject.name); // Output: John Doe
console.log(myObject['age']); // Output: 30

Modifying Object Properties

To modify an object property, simply reassign the value for that key.

myObject.age = 31;
console.log(myObject.age); // Output: 31

Adding and Deleting Properties

You can add a new property to an object using the dot notation or bracket notation. To delete a property, use the delete keyword.

myObject.newProperty = 'value';
console.log(myObject); // Output: { name: 'John Doe', age: 31, isStudent: false, hobbies: ['reading', 'gaming'], newProperty: 'value' }
delete myObject.isStudent;
console.log(myObject); // Output: { name: 'John Doe', age: 31, hobbies: ['reading', 'gaming'], newProperty: 'value' }

Object Methods

Objects can also have methods, which are functions associated with the object. A method is defined by using a function within the curly braces of an object literal.

const myObject = {
name: 'John Doe',
age: 30,
greet: function () {
console.log(`Hello! I am ${this.name}.`);
},
};
myObject.greet(); // Output: Hello! I am John Doe.

Prototypes and Inheritance

Every object in JavaScript has a prototype, which is another object that serves as a source of properties for the object. The prototype of an object can be accessed using the prototype property. When you create an object using the Object.create() method, it inherits properties from the specified prototype object.

const parent = { greet: function () { console.log('Hello!'); } };
const child = Object.create(parent);
child.greet(); // Output: Hello!

Worked Example

Let's create a simple object that represents a car with properties for its make, model, year, and color. Access and modify these properties, and add a method to calculate the car's age.

const car = {
make: 'Toyota',
model: 'Camry',
year: 2015,
color: 'Blue',
getAge: function () {
const currentYear = new Date().getFullYear();
return currentYear - this.year;
},
};

// Access properties
console.log(car.make); // Output: Toyota
console.log(car['model']); // Output: Camry

// Modify properties
car.year = 2016;
console.log(car.getAge()); // Output: 5

// Add a new property
car.mileage = 30000;
console.log(car); // Output: { make: 'Toyota', model: 'Camry', year: 2016, color: 'Blue', getAge: [Function], mileage: 30000 }

Common Mistakes

  1. Forgetting property quotes: Property keys should be enclosed in either single or double quotes.

Incorrect: const myObject = { name age: 30 };

Correct: const myObject = { name: 'age', age: 30 };

  1. Using invalid property keys: Property keys cannot be numbers without quotes, and they must not start with a number.

Incorrect: const myObject = { 1name: 'John' };

Correct: const myObject = { '1name': 'John' }; or const myObject = { name: 'John', oneName: 1 };

  1. Accessing non-existent properties: Always check if a property exists before accessing it to avoid errors.

Incorrect: console.log(myObject.nonexistentProperty);

Correct: if (myObject.hasOwnProperty('nonexistentProperty')) { console.log(myObject.nonexistentProperty); }

  1. Modifying object literals passed as arguments: When passing an object literal to a function, be aware that modifying the object within the function will affect the original object outside of it. If you want to avoid this behavior, create a copy of the object before making modifications.

Incorrect:

function modifyObject(obj) {
obj.age = 31; // Modifies the original object
}
const myObject = { age: 30 };
modifyObject(myObject);
console.log(myObject.age); // Output: 31

Correct:

function modifyObject(obj) {
const copy = { ...obj }; // Create a copy of the object
copy.age = 31;
return copy;
}
const myObject = { age: 30 };
console.log(modifyObject(myObject).age); // Output: 31, but myObject remains unmodified
  1. Using var instead of const or let: Using var can lead to issues with function scope and hoisting. It's recommended to use const for immutable values and let for mutable values.

Incorrect:

function example() {
var myVariable = 'Hello';
}
example();
console.log(myVariable); // Output: undefined

Correct:

function example() {
const myVariable = 'Hello';
}
example();
console.log(myVariable); // Output: ReferenceError: myVariable is not defined

Practice Questions

  1. Create an object representing a person with properties for name, age, and occupation. Access and modify these properties. Add a method to calculate the person's retirement age (assuming retirement age is 65).
  2. Given the following objects, create a new object containing only properties that are common between them:
const obj1 = { name: 'John', age: 30, occupation: 'Engineer' };
const obj2 = { name: 'Jane', age: 28, hobbies: ['reading', 'painting'] };
  1. Write a function that accepts an object as an argument and returns a new object with all properties sorted alphabetically by key.
  2. Create an object representing a shopping cart with methods to add an item, remove an item, and calculate the total cost of items in the cart.

FAQ

  1. Can I create an empty object in JavaScript?

Yes! Simply use {}.

  1. What happens if I try to assign a property with the same name twice?

The later assignment will overwrite the previous value.

  1. How can I check if an object has a specific property?

Use the hasOwnProperty() method: if (myObject.hasOwnProperty('propertyName')) { ... }.

  1. What is the difference between Object.create() and an object literal?

An object literal creates a new object with properties defined directly within its syntax, while Object.create() creates a new object with properties inherited from another object (the prototype).

  1. How do I clone an object in JavaScript?

You can use the spread operator (...) or the JSON.parse(JSON.stringify()) method to create a copy of an object.

  1. What is the difference between dot notation and bracket notation when accessing object properties?

Dot notation is used when the property name is a valid JavaScript identifier, while bracket notation can be used with any valid string as a property key.

  1. How do I set the prototype of an object in JavaScript?

To set the prototype of an object, assign another object to its prototype property: myObject.prototype = anotherObject.

  1. What is the difference between shallow copy and deep copy in JavaScript?

A shallow copy creates a new object with references to the original object's properties, while a deep copy creates a new object with copies of the original object's properties (and their own properties, recursively).

  1. How can I iterate over an object's properties in JavaScript?

You can use a for...in loop or the Object.keys(), Object.values(), and Object.entries() methods to iterate over an object's properties.

object literal (JavaScript) | JavaScript | XQA Learn