Objects
Learn about objects, their properties, and methods. Understand how to create and manipulate objects.
JavaScript Object Properties
Object Properties Explained
In JavaScript, an object is a collection of key-value pairs. These key-value pairs are called properties. The 'key' (also called the property name) is typically a string (though it can be a Symbol), and the 'value' can be any valid JavaScript data type, including:
- Primitive values (strings, numbers, booleans, null, undefined)
- Other objects
- Arrays
- Functions
Think of an object as a container that holds related data and functionality together. The properties define the characteristics and behaviors of the object.
Defining, Accessing, Modifying, and Deleting Properties
Defining Properties
There are several ways to define properties in a JavaScript object:
Object Literal Notation
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
greet: function() {
console.log("Hello, my name is " + this.firstName);
}
};
This is the most common and concise way to create objects and define their properties.
Dot Notation
const car = {};
car.make = "Toyota";
car.model = "Camry";
car.year = 2023;
You can add properties to an existing object using dot notation. If the property doesn't exist, it's created.
Bracket Notation
const animal = {};
animal["species"] = "Dog";
animal["breed"] = "Golden Retriever";
Bracket notation is useful when the property name is stored in a variable or contains characters that are not valid in dot notation (e.g., spaces or special characters).
Accessing Properties
You can access property values using either dot notation or bracket notation:
Dot Notation
console.log(person.firstName); // Output: John
console.log(car.year); // Output: 2023
Bracket Notation
console.log(person["lastName"]); // Output: Doe
console.log(animal["species"]); // Output: Dog
const propertyName = "age";
console.log(person[propertyName]); // Output: 30 (using a variable)
Modifying Properties
You can change the value of an existing property using assignment:
Dot Notation
person.age = 31; // Changes the age to 31
console.log(person.age); // Output: 31
Bracket Notation
animal["breed"] = "Labrador"; // Changes the breed to Labrador
console.log(animal["breed"]); // Output: Labrador
Deleting Properties
You can remove a property from an object using the delete
operator:
Dot Notation or Bracket Notation
delete person.age; // Removes the age property
console.log(person.age); // Output: undefined (property no longer exists)
delete animal["breed"]; // Removes the breed property
console.log(animal["breed"]); // Output: undefined
Deleting a property removes it entirely from the object. Accessing a deleted property will return undefined
.