How do I remove a key from a JavaScript object?

 

You can remove a key from a JavaScript object using the delete keyword. Here's how you can do it with an example:

javascript
// Create an example object var person = { firstName: "John", lastName: "Doe", age: 30, }; // Remove the 'age' key from the object delete person.age; // Check if the 'age' key is gone if (!person.age) { console.log("The 'age' key has been removed."); } else { console.log("The 'age' key is still present."); } // Print the updated object console.log(person);

In this example:

  1. We create an object named person with three key-value pairs: firstName, lastName, and age.

  2. We use the delete keyword to remove the age key from the person object: delete person.age;.

  3. We then check if the age key is still present in the object using if (!person.age). If it's not present, we print a message indicating that it has been removed.

  4. Finally, we print the updated person object to the console, which will not contain the age key anymore.

When you run this code, you'll see that the age key is removed from the person object, and the output will confirm this.

Comments