In PHP, you can directly remove an item from an array using unset function. But there is no unset function in JavaScript. But there is another function that will remove a variable. It’s called delete. Removing variables isn’t the only thing it does. It can also remove items from a JSON array in JavaScript.
It’s usage is simple. Just pass the array variable with the name of the key. Like this :
delete arr[keyname];
Examples
This is the array we’ll use for examples :
var arr = {
"Gohan" : "Yipee",
"Vegeta" : "Goku"
}
We first delete the key “Gohan” :
delete arr["Gohan"];
Now, when you output the array arr, you will not see the key “Gohan” with the value “Yipee”. Here’s how the array will become after the above code is executed :
{
"Vegeta" : "Goku"
}
Easy as that. You can also use delete for removing variables and functions. But you can’t remove the variable “window”. Example :
var uid = "abc";
delete uid;
Now when you access the variable “uid”, you will get the “undefined” error :
console.log(uid);
// ReferenceError: uid is not defined
delete returns “true” when the deleting was successful and “false” when not successful. You will get “false” when you try to delete variables like window.