Object properties in JavaScript allow you to associate values with keys within an object. Objects are fundamental data structures that represent a collection of related data and functionalities.
Objects can be created using object literals or constructor functions.
1. Object Literal
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
var person = new Person("John", "Doe", 30);
Object properties can be accessed using dot notation or square bracket notation.
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
console.log(person.firstName); // John
console.log(person["lastName"]); // Doe
Properties can be modified by assigning new values to them.
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
person.age = 31;
person["age"] = 31;
console.log(person.age); // 31
console.log(person["age"]); // 31
You can add new properties to an object by assigning a value to a new key.
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
person.city = "New York";
person["city"] = "New York";
console.log(person.city); // New York
console.log(person["city"]); // New York
Properties can be deleted using the delete operator.
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
delete person.age;
console.log(person); // firstName: "John", lastName: "Doe"
console.log(person.age); // undefined
You can iterate through an object's properties using loops or the for...in loop.
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
for (var key in person) {
console.log(key + ": " + person[key]);
}
You can check if an object has a specific property using the hasOwnProperty() method.
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
if (person.hasOwnProperty("age")) {
console.log("Age property exists.");
}
ES6 introduced computed property names, allowing dynamic property names during object creation.
let propertyName = "color";
let car = {
[propertyName]: "blue"
};
console.log(car.color); // blue
Object properties are key-value pairs that enable you to store and access related data within objects. They are fundamental for creating complex data structures in JavaScript.