AppDividend
Latest Code Tutorials

How to Remove Key From JavaScript Object

0

To remove the key from Object in Javascript, delete operator. Javascript Delete Operator deletes a property from an object. The delete operator enables you to remove the property from an object. The delete only returns false when a property can not be deleted.

How to Remove Key From JavaScript Object

JavaScript delete operator deletes a key from an object; if no more references to the same key are held, it is eventually released automatically.

Syntax

delete object.keyname;

# OR

delete object["keyname"];

Parameters

object

The name of the object or an expression evaluating to an object.

property

The property to delete.

Return Value

The delete operator returns true for all cases except when the property is the own non-configurable property, in which case, the false is returned in the non-strict mode.

Example to remove the key from Object in JavaScript

Write a following code in the app.js file.

// app.js

let obj = {
  name: 'Krunal',
  age: 27,
  education: 'Engineer'
};

console.log(obj)

delete obj.age;
console.log('After removing a key using Object');
console.log(obj);

Output

{ name: 'Krunal', age: 27, education: 'Engineer' }
After removing a key using Object
{ name: 'Krunal', education: 'Engineer' }

In this example, we have tried to remove the age key from the Object using the delete operator in the output, and you can see that we have successfully removed the key.

However, it is essential to consider the following scenarios.

  1. If the key which you are trying to delete does not exist, delete will not have any effect and will return true.
  2. If the key with the same name exists on the Object’s prototype chain, then, after deletion, the Object will use the key from the prototype chain (in other words, delete only affects its keys).
  3. Any key declared with var cannot be deleted from the global scope or the function’s scope.
    1. As such, delete cannot delete any methods in the global scope (whether this is part of a function definition or a function expression).
    2. Functions that are part of the Object (apart from the global scope) can be deleted with delete.
  4. Any key declared with let or const cannot be deleted from the scope within which they were defined.
  5. Non-configurable keys cannot be removed. This includes properties of inbuilt objects like Math, Array, Object, and properties that are created as non-configurable with methods like Object.defineProperty().

That is it for removing a key from JavaScript Object.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.