Selected topic
Objects
Prefer practical output? Use related tools below while reading.
=======================
In JavaScript, an object is a collection of key-value pairs. Each key is unique and corresponds to a specific value.
### Creating Objects
There are several ways to create objects in JavaScript:
#### Using the Object Constructor
javascript
let person = new Object();
person.name = 'John Doe';
person.age = 30;javascript
let person = {
name: 'John Doe',
age: 30
};name and age.### Properties
Properties are the key-value pairs that make up an object. They can be accessed using dot notation (e.g., person.name) or bracket notation (e.g., person['name']).
#### Accessing Properties
javascript
let person = {
name: 'John Doe',
age: 30
};console.log(person.name); // John Doe
console.log(person.age); // 30
javascript
let person = {
name: 'John Doe',
age: 30
};person.age = 31;
console.log(person.age); // 31
Methods are functions that belong to an object. They can be defined using the function keyword or the shorthand syntax () => { ... }.
#### Defining Methods
javascript
let person = {
name: 'John Doe',
age: 30,sayHello: function() {
console.log('Hello, my name is ' + this.name);
},
printAge: () => console.log(this.age)
};
person.sayHello(); // Hello, my name is John Doe
person.printAge(); // 30
Objects have several built-in methods that can be used to manipulate them. Here are a few examples:
#### Object.keys(): Returns an array of the object's property names.
javascript
let person = {
name: 'John Doe',
age: 30
};console.log(Object.keys(person)); // ['name', 'age']
Object.values(): Returns an array of the object's property values.javascript
let person = {
name: 'John Doe',
age: 30
};console.log(Object.values(person)); // ['John Doe', 30]
Object.assign(): Copies properties from one or more objects to another.javascript
let person1 = {
name: 'John Doe',
age: 30
};let person2 = {};
Object.assign(person2, person1);
console.log(person2); // {name: 'John Doe', age: 30}