JavaScript Object is a collection of related data and functionality. Objects are used to store collections of various data and complex entities.
To create an object in JavaScript, we have to first declare a variable. After declaring the variable, we can assign properties to the variable by passing the properties into curly braces {…}
.
For example:
let newUser = {
fullName: "Sheldon Cooper",
age: 27,
location: "United States"
}
In the example above, you will notice that each property of the object has two data separated by a semi-colon age: 27
, the word on the left “age” is called the “key” while the number on the right “27” is called the value. They are collectively called key-value pairs. Each key-value pair is also referred to as property of an object.
The key can be used to modify the value if selected with a dot notation.
For example
newUser.age ;
You can also modify the value of the selected key by assigning it a new value.
newUser.age = 31; //the age of newUser is now 31
In the example above, we were able to access the key to the key-value pair and change its value from 27
to 31
.
However, in some cases, you might need to delete or remove a property from an object. You can achieve this by using the delete
operator keyword to delete property of an object. The delete
operator is only effective on an object’s properties. It has no effect on variables or functions.
To delete the property of an object, use the delete
operator such as in the example below:
delete newUser.age ; //"age" property of the object has been deleted
To check if the property has been deleted, log the object in the developer’s console using:
console.log(newUser); //"age" property has been deleted.
When you log the newUser
variable into the console, you'd observe that the age property and it's value has been deleted.
See full code snippet below
let newUser = {
fullName: "Sheldon Cooper",
age: 27,
location: United States
};
delete newUser.age;
console.log(newUser);
Top comments (4)
you can also do it with destructuring to preserve the original object
I love how i interpreted your code in english in my head
A good summary!
It's also possible to delete items from arrays too using
delete
.Yes, that's possible