
JavaScript Objects
The JavaScript object is a collection of key-value pairs, where the keys are strings and the values can be any data type, including other objects. Objects are defined using curly braces {} and can contain zero or more key-value pairs.
Here’s an example of an object with three key-value pairs:
let person = {
name: 'John',
age: 30,
hobbies: ['reading', 'running', 'cooking']
};
You can access individual properties of an object using dot notation or square bracket notation. For example, to access the name and age properties of the person object above, you would use:
console.log(person.name); // Output: 'John'
console.log(person['age']); // Output: 30
You can also add, remove, or modify properties of an object using dot notation or square bracket notation. Here are some examples:
person.job = 'teacher'; // adds the 'job' property to the object
console.log(person); // Output: {name: 'John', age: 30, hobbies: ['reading', 'running', 'cooking'], job: 'teacher'}
delete person.hobbies; // removes the 'hobbies' property from the object
console.log(person); // Output: {name: 'John', age: 30, job: 'teacher'}
person['age'] = 35; // modifies the 'age' property of the object
console.log(person); // Output: {name: 'John', age: 35, job: 'teacher'}
You can also iterate over the properties of an object using a for…in loop. For example, to loop through the properties of the person object above, you would use:
for (let prop in person) {
console.log(prop + ': ' + person[prop]);
}
This would output:
name: John
age: 35
job: teacher