JavaScript Objects
JavaScript Objects
- In JavaScript, an object is an unordered collection of key-value pairs. Each key-value pair is called a property.
- The key of a property can be a string. And the value of a property can be any value, e.g., a string, a number, an array, and even a function.
- To create an object we can use the object literal notation as below.
- To create an object with properties, we use the
key:value
within the curly braces.
person.js |
---|
| let person = {
firstName: 'John',
lastName: 'Doe'
};
|
Accessing Properties
The dot notation .
- To access properties of an object we can use dot notation. This is the most common way that we usually use
person.js |
---|
| let person = {
firstName: 'John',
lastName: 'Doe'
};
console.log(person.firstName);
console.log(person.lastName);
//John
//Doe
|
Array-Like Notation []
- There is also has another way to access the value of an object’s property via the array-like notation:
| let person = {
firstName: 'John',
lastName: 'Doe'
};
console.log(person['firstName']);
console.log(person['lastName']);
//John
//Doe
|
- When property names contain spaces, we can place it inside quotes.
person.js |
---|
| let person = {
'first name': 'John',
'last name': 'Doe'
};
console.log(person.'first name');
console.log(person.'last name');
//John
//Doe
|
Note: This will not work if we use dot .
Modifying the value of a property
- To change the value of a property, you use the assignment operator =
person.js |
---|
| let person = {
firstName: 'John',
lastName: 'Doe'
};
person.firstName = 'Tom'
console.log(person.firstName);
console.log(person.lastName);
//Tom
//Doe
|
Add A Property To Object
- We can add a property to an object after object creation.
person.js |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | let person = {
firstName: 'John',
lastName: 'Doe'
};
person.age = 25;
console.log(person.firstName);
console.log(person.lastName);
console.log(person.age);
//John
//Doe
//25
|
Delete A Property From Object
- To delete a property of an object, you use the
delete
operator:
person.js |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | let person = {
firstName: 'John',
lastName: 'Doe'
};
person.age = 25;
delete person.age;
console.log(person.firstName);
console.log(person.lastName);
console.log(person.age);
//John
//Doe
//undefined
|
Checking if a property exists
- To check if a property exists in an object, you use the
in
operator:
person.js |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | let person = {
firstName: 'John',
lastName: 'Doe'
};
console.log(person.firstName);
console.log(person.lastName);
console.log('lastName' in person);
console.log('age' in person);
//John
//Doe
//true
//false
|
See Also
References