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...
var 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 the key-value pairs. Each key-value pair are also referred to as the property of an object.
The key can be used to modify the value if selected with a dot notation.
For example...
newUser.age;
We can also modify the value of the selected key by assigning it a new value
newUser.age = 31; //age of newUser is now set to 31
In the example above, we were able to access the key of the key-value pair and change its value from “27” to “31”.
However, in some cases, we might need to delete or remove a property from an object. We can achieve this by using the delete operator keyword to delete the 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) ; //log to check if “age” property has been deleted.
Now you will see that the age property has been deleted.
Access the full code below...
var newUser = { fullName: 'Sheldon Cooper', age: 27, location: United States' } delete newUser.age ; //'age' property of the object has been deleted console.log(newUser) ; //log to check if 'age' property has been deleted.
Conclusion:
The delete operator is designed to work with object properties only, therefore it has no effects on variables or functions. The delete operator deletes the value of the property and the property itself. The property cannot be used again after deletion.