Objects and properties
A JavaScript object is a collection of named values. The named values — also called properties — can be of any type: strings, numbers, booleans, dates, functions, arrays, or even other objects.
Object literals
The simplest way to create an object is using an object literal:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
hobbies: ['reading', 'coding'],
address: {
city: 'New York',
country: 'USA'
},
greet() {
return `Hello, I'm ${this.firstName}`;
}
};
Accessing properties
You can access object properties using dot notation or bracket notation:
console.log(person.firstName);
console.log(person['lastName']);
const key = 'age';
console.log(person[key]);
Note: Accessing a non-existent property returns undefined. Use the in operator or hasOwnProperty() to check if a property exists.
Object methods
JavaScript provides several static methods for working with objects:
const obj = { a: 1, b: 2, c: 3 };
Object.keys(obj);
Object.values(obj);
Object.entries(obj);
const clone = { ...obj };
const merged = { ...obj, d: 4 };
const { a, b, c } = obj;