Beginner25 min read

Objects

Understand JavaScript objects — creating, accessing, and modifying key-value pairs, and using methods.

Creating Objects

An object is a collection of key-value pairs. While arrays store ordered lists of values accessed by index, objects store named values accessed by key. Objects are one of the most important data structures in JavaScript — almost everything in the language is built on them.

The most common way to create an object is with an object literal — curly braces containing comma-separated properties:

javascript
const person = {
  name: 'Alice',
  age: 30,
  city: 'Paris',
};

Each property has a key (also called a name) and a value. Keys are strings (or Symbols), and values can be anything — numbers, strings, booleans, arrays, other objects, or even functions.

When a variable name matches the key name, you can use shorthand property names:

javascript
const name = 'Bob';
const age = 25;

const person = { name, age };
// Same as: { name: 'Bob', age: 25 }

You can use computed property names when the key is dynamic:

javascript
const field = 'email';
const user = {
  [field]: 'bob@example.com',
};
console.log(user.email); // 'bob@example.com'

Nested objects are objects within objects, useful for representing structured data:

javascript
const student = {
  name: 'Charlie',
  grades: {
    math: 92,
    english: 88,
    science: 95,
  },
};

console.log(student.grades.math); // 92

Accessing Properties

There are two ways to access properties on an object:

1. Dot notation — the most common and readable way:

javascript
const person = { name: 'Alice', age: 30 };
console.log(person.name); // 'Alice'
console.log(person.age);  // 30

2. Bracket notation — uses a string (or expression) inside square brackets:

javascript
console.log(person['name']); // 'Alice'
console.log(person['age']);  // 30

Bracket notation is required in these situations:

  • Dynamic keys — when the property name is stored in a variable:

    javascript
    const key = 'name';
    console.log(person[key]); // 'Alice'
  • Keys with spaces or special characters:

    javascript
    const data = { 'first name': 'Alice', 'last-name': 'Smith' };
    console.log(data['first name']); // 'Alice'
    // data.first name — would cause a syntax error!
  • Keys that are numbers:

    javascript
    const scores = { 1: 'gold', 2: 'silver', 3: 'bronze' };
    console.log(scores[1]); // 'gold'

Accessing a property that does not exist returns undefined:

javascript
console.log(person.email); // undefined

Optional chaining (?.) is a safe way to access nested properties without risking an error if an intermediate property is undefined or null:

javascript
const user = { profile: { bio: 'Developer' } };
console.log(user.profile?.bio);    // 'Developer'
console.log(user.settings?.theme); // undefined (no error)

Without ?., accessing user.settings.theme would throw a TypeError because user.settings is undefined.

Modifying Objects

Objects are mutable — you can add, update, and remove properties after creation.

Adding properties:

javascript
const person = { name: 'Alice' };
person.age = 30;           // dot notation
person['email'] = 'a@b.c'; // bracket notation

Updating properties:

javascript
person.name = 'Bob'; // overwrite existing value

Removing properties with the delete operator:

javascript
delete person.email;
console.log(person.email); // undefined

JavaScript provides useful static methods on the Object class for working with properties:

  • Object.keys(obj) — returns an array of all property names:

    javascript
    Object.keys(person); // ['name', 'age']
  • Object.values(obj) — returns an array of all values:

    javascript
    Object.values(person); // ['Bob', 30]
  • Object.entries(obj) — returns an array of [key, value] pairs:

    javascript
    Object.entries(person); // [['name', 'Bob'], ['age', 30]]

Checking if a property exists:

  • The in operator checks for a property in the object and its prototype chain:

    javascript
    'name' in person; // true
    'email' in person; // false
  • hasOwnProperty() checks only the object itself (not the prototype):

    javascript
    person.hasOwnProperty('name'); // true

These tools make it easy to inspect and iterate over objects dynamically.

Methods

When a function is stored as a property of an object, it is called a method:

javascript
const calculator = {
  result: 0,
  add: function(n) {
    this.result += n;
  },
  reset: function() {
    this.result = 0;
  },
};

calculator.add(5);
calculator.add(3);
console.log(calculator.result); // 8

The this keyword inside a method refers to the object the method is called on. In the example above, this.result refers to calculator.result.

ES6 introduced a method shorthand syntax that is cleaner and more commonly used:

javascript
const calculator = {
  result: 0,
  add(n) {
    this.result += n;
  },
  reset() {
    this.result = 0;
  },
};

This is exactly the same as the longer add: function(n) { ... } syntax but more concise.

Methods can also return values, just like regular functions:

javascript
const person = {
  firstName: 'Alice',
  lastName: 'Smith',
  fullName() {
    return this.firstName + ' ' + this.lastName;
  },
};

console.log(person.fullName()); // 'Alice Smith'

Understanding this can be tricky — its value depends on how the function is called, not where it is defined. For now, just remember that inside an object method called with dot notation (person.fullName()), this refers to the object before the dot (person).

Objects in Action

html
<div id="card"></div>

<script>
  const person = {
    name: 'Alice',
    role: 'Developer',
    skills: ['JavaScript', 'HTML', 'CSS'],
    introduce() {
      return "Hi, I'm " + this.name + ", a " + this.role + ".";
    },
    listSkills() {
      return 'Skills: ' + this.skills.join(', ');
    },
  };

  const card = document.getElementById('card');
  const heading = document.createElement('h2');
  heading.textContent = person.introduce();
  card.appendChild(heading);

  const para = document.createElement('p');
  para.textContent = person.listSkills();
  card.appendChild(para);

  // Iterate over properties
  const details = document.createElement('ul');
  for (const [key, value] of Object.entries(person)) {
    if (typeof value !== 'function') {
      const li = document.createElement('li');
      li.textContent = key + ': ' + value;
      details.appendChild(li);
    }
  }
  card.appendChild(details);
</script>

How do you access a property called 'first name' (with a space) on an object?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.