Module: Arrays and Objects

Object Properties

JavaScript Essentials: Arrays and Objects - Object Properties

This document covers object properties in JavaScript.

What are Object Properties?

Objects in JavaScript are collections of key-value pairs. These key-value pairs are called properties.

  • Key: The name of the property. It's always a string (or a Symbol, but we'll focus on strings here).
  • Value: The data associated with that property. This can be any JavaScript data type: numbers, strings, booleans, arrays, other objects, functions, etc.

Think of an object like a real-world object with characteristics. For example, a car has properties like color, make, model, and year.

Creating Objects and Defining Properties

There are several ways to create objects and define their properties:

1. Object Literal Notation:

This is the most common and concise way to create objects.

const myCar = {
  make: "Toyota",
  model: "Camry",
  year: 2023,
  color: "Silver",
  isElectric: false
};

2. Using the new Object() Constructor:

Less common, but still valid.

const myCar = new Object();
myCar.make = "Toyota";
myCar.model = "Camry";
myCar.year = 2023;
myCar.color = "Silver";
myCar.isElectric = false;

3. Using a Function Constructor:

Useful for creating multiple objects with the same structure.

function Car(make, model, year, color) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.color = color;
  this.isElectric = false; // Default value
}

const car1 = new Car("Honda", "Civic", 2022, "Blue");
const car2 = new Car("Tesla", "Model 3", 2024, "Red");

4. Using Classes (ES6 and later):

A more modern and structured approach to object creation.

class Car {
  constructor(make, model, year, color) {
    this.make = make;
    this.model = model;
    this.year = year;
    this.color = color;
    this.isElectric = false;
  }
}

const car1 = new Car("Honda", "Civic", 2022, "Blue");
const car2 = new Car("Tesla", "Model 3", 2024, "Red");

Accessing Object Properties

There are two main ways to access object properties:

1. Dot Notation:

The most common and readable way.

console.log(myCar.make);   // Output: Toyota
console.log(myCar.year);   // Output: 2023

2. Bracket Notation:

Useful when the property name is stored in a variable or contains characters that are not allowed in dot notation (e.g., spaces).

const propertyName = "model";
console.log(myCar[propertyName]); // Output: Camry

const myObject = { "first name": "John", "last name": "Doe" };
console.log(myObject["first name"]); // Output: John

Modifying Object Properties

You can easily modify the value of an existing property:

myCar.color = "Black";
console.log(myCar.color); // Output: Black

Adding New Properties

You can add new properties to an object after it's been created:

myCar.engineSize = "2.5L";
console.log(myCar.engineSize); // Output: 2.5L

Deleting Properties

Use the delete operator to remove a property from an object:

delete myCar.isElectric;
console.log(myCar.isElectric); // Output: undefined

Checking for Property Existence

There are a few ways to check if an object has a specific property:

1. in operator:

Checks if a property exists in the object or its prototype chain.

console.log("make" in myCar); // Output: true
console.log("isElectric" in myCar); // Output: false (because it was deleted)

2. hasOwnProperty() method:

Checks if a property exists directly on the object itself, not in its prototype chain.

console.log(myCar.hasOwnProperty("make")); // Output: true
console.log(myCar.hasOwnProperty("toString")); // Output: false (inherited from prototype)

3. Checking for undefined:

This is a simple but potentially unreliable method. If a property exists but has a value of undefined, this check will return false even though the property exists.

console.log(myCar.someNonExistentProperty === undefined); // Output: true

Iterating Through Object Properties

You can iterate through the properties of an object using several methods:

1. for...in loop:

Iterates over all enumerable properties of an object, including inherited properties.

for (let key in myCar) {
  if (myCar.hasOwnProperty(key)) { // Important to check hasOwnProperty
    console.log(key + ": " + myCar[key]);
  }
}

2. Object.keys():

Returns an array of the object's own enumerable property names.

const keys = Object.keys(myCar);
keys.forEach(key => {
  console.log(key + ": " + myCar[key]);
});

3. Object.values():

Returns an array of the object's own enumerable property values.

const values = Object.values(myCar);
values.forEach(value => {
  console.log(value);
});

4. Object.entries():

Returns an array of [key, value] pairs for the object's own enumerable properties.

const entries = Object.entries(myCar);
entries.forEach(([key, value]) => {
  console.log(key + ": " + value);
});

Summary

Understanding object properties is fundamental to working with JavaScript. You've learned how to create, access, modify, delete, and iterate through them. Choosing the right method for accessing and iterating depends on your specific needs and the context of your code. Remember to use hasOwnProperty() when iterating to avoid unexpected behavior from inherited properties.