The delete
operator in JavaScript is used to delete an object property or an element from an array.
The syntax of the delete
operator is as follows:
delete object.property; // deletes a property from an object
delete object[index]; // deletes an element from an array
Here’s an example that shows how to use the delete
operator to delete a property from an object:
const myObject = { a: 1, b: 2, c: 3 };
delete myObject.b; // deletes the 'b' property from myObject
console.log(myObject); // { a: 1, c: 3 }
In this example, we first create an object myObject
with three properties: a
, b
, and c
. We then use the delete
operator to delete the b
property from the object. Finally, we log the updated myObject
to the console, which shows that the b
property has been deleted.
Similarly, here’s an example that shows how to use the delete
operator to delete an element from an array:
const myArray = [1, 2, 3];
delete myArray[1]; // deletes the element at index 1
console.log(myArray); // [1, undefined, 3]
In this example, we first create an array myArray
with three elements: 1
, 2
, and 3
. We then use the delete
operator to delete the element at index 1
. Finally, we log the updated myArray
to the console, which shows that the element at index 1
has been deleted and replaced with undefined
.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.