Introduction to Objects

In JavaScript, objects are essentially collections of key/value pairs. These values can include properties and methods, incorporating all other JavaScript data types such as strings, numbers, and Booleans.

Every object in JavaScript inherits from the parent Object constructor. The Object constructor comes with a suite of handy built-in methods that simplify working with individual objects. Unlike methods for arrays, such as sort() and reverse(), which are called on array instances, Object methods are called directly on the Object constructor itself, with the object instance passed as an argument. These are known as static methods.

Creating Objects

Object Literals

The simplest way to create an object is using an object literal.

object-literals.js
const person = {
  name: "John",
  age: 30,
  job: "Developer"
};

console.log(person);

Using the Object Constructor

Another way to create an object is by using the Object constructor.

object-constructor.js
const person = new Object();
person.name = "John";
person.age = 30;
person.job = "Developer";

console.log(person);

Accessing Object Properties

Dot Notation

The most common way to access properties is using dot notation.

dot-notation.js
const person = {
  name: "John",
  age: 30,
  job: "Developer"
};

console.log(person.name); // "John"
console.log(person.age); // 30

Bracket Notation

You can also access properties using bracket notation, which is useful when property names are dynamic or not valid identifiers.

bracket-notation.js
const person = {
  name: "John",
  age: 30,
  job: "Developer"
};

console.log(person["name"]); // "John"
console.log(person["age"]); // 30

const property = "job";
console.log(person[property]); // "Developer"

Modifying Object Properties

Adding and Updating Properties

You can add new properties or update existing ones using either dot or bracket notation.

modify-obj-prop.js
const person = {
  name: "John",
  age: 30
};

person.job = "Developer"; // Adding a new property
person.age = 31; // Updating an existing property

console.log(person);

Deleting Properties

To remove a property from an object, use the delete operator.

del-props.js
const person = {
  name: "John",
  age: 30,
  job: "Developer"
};

delete person.job;

console.log(person); // { name: "John", age: 30 }

Checking for Properties

in Operator

The in operator checks if a property exists in an object.

in-operator.js
const person = {
  name: "John",
  age: 30
};

console.log("name" in person); // true
console.log("job" in person); // false

hasOwnProperty() Method

The hasOwnProperty() method checks if a property exists as a direct property of the object, not inherited through the prototype chain.

has-own-prop-obj.js
const person = {
  name: "John",
  age: 30
};

console.log(person.hasOwnProperty("name")); // true
console.log(person.hasOwnProperty("job")); // false

Iterating Over Properties

for...in Loop

The for...in loop iterates over all enumerable properties of an object, including inherited properties.

for-in-loop-js
const person = {
  name: "John",
  age: 30,
  job: "Developer"
};

for (let key in person) {
  if (person.hasOwnProperty(key)) {
    console.log(`${key}: ${person[key]}`);
  }
}

Object.keys(), Object.values(), and Object.entries()

These methods return arrays of the object's keys, values, and key-value pairs, respectively.

object-methods.js
const person = {
  name: "John",
  age: 30,
  job: "Developer"
};

console.log(Object.keys(person)); // ["name", "age", "job"]
console.log(Object.values(person)); // ["John", 30, "Developer"]
console.log(Object.entries(person)); // [["name", "John"], ["age", 30], ["job", "Developer"]]

Practical Examples

Managing a To-Do List

Using objects to manage a to-do list with tasks and their statuses.

todo-list.js
const todoList = {
  tasks: [
    { task: "Learn JavaScript", completed: false },
    { task: "Build a project", completed: false }
  ],
  addTask(task) {
    this.tasks.push({ task, completed: false });
  },
  completeTask(taskName) {
    const task = this.tasks.find(t => t.task === taskName);
    if (task) {
      task.completed = true;
    }
  },
  getTasks() {
    return this.tasks;
  }
};

todoList.addTask("Review code");
todoList.completeTask("Learn JavaScript");
console.log(todoList.getTasks());

Game Character Stats

Using objects to store and update game character statistics.

game-char-stats.js
const character = {
  name: "Archer",
  level: 1,
  health: 100,
  stats: {
    strength: 10,
    agility: 15,
    intelligence: 12
  },
  levelUp() {
    this.level++;
    this.health += 20;
    this.stats.strength += 2;
    this.stats.agility += 3;
    this.stats.intelligence += 1;
  }
};

character.levelUp();
console.log(character);

Notes:

  • Objects are a fundamental part of JavaScript and are used to store collections of data and more complex entities.
  • Object Literals are the most common way to create objects, providing a clean and concise syntax.
  • Bracket Notation is useful for dynamic property access or when property names are not valid identifiers.
  • Object.keys, Object.values, and Object.entries are powerful methods for working with object properties.

FAQ

Q: What is the difference between dot notation and bracket notation?

A: Dot notation is more concise and easier to read, but can only be used with valid identifier property names. Bracket notation is more flexible and allows for dynamic property names and property names that are not valid identifiers.

Q: How do I check if an object has a specific property?

A: You can use the in operator or the hasOwnProperty method to check if an object has a specific property.

Q: Can objects in JavaScript have methods?

A: Yes, objects can have methods, which are functions that belong to the object. These methods can be used to manipulate the object's properties or perform other actions related to the object.

Q: How can I iterate over an object's properties?

A: You can use a for...in loop to iterate over an object's properties, or use Object.keys, Object.values, and Object.entries to work with arrays of the object's keys, values, and key-value pairs, respectively.