Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't remove LocalStorage Item with .removeItem

I'm trying to remove a localStorage with .removeItem(keys) but it's said the localStorage keys is not defined. I'm trying to make a simple localStorage again like below, and then trying to removeItem again, still the same problem. What's wrong?

<html>
<head>
    <script>
        localStorage.test = "good";
        console.log(localStorage.test);
        localStorage.removeItem(test);
    </script>
</head>

The browser said, "Uncaught ReferenceError: test is not defined". I'm trying using window.localStorage.clear(), it's work, but I want to specify which localStorage I want to delete.

like image 635
Jepi Avatar asked Jan 31 '23 00:01

Jepi


1 Answers

The reason you are running into an error is because, test is not available in the scope of code ( and a reference error is thrown, when you try to access a variable that is not defined yet). In your case it lives on localStorage.test because you are attaching it directly to localStorage object.

If you had used localStorage.removeItem(localStorage.test); instead, you would not have come across the error.

And it is not a good idea to set properties on the localStorage object directly. Instead use setItem to store data in local storage.

var value = "good";

localStorage.setItem('test', value); // set the item

console.log(localStorage.getItem('test')); // retrieve the item

localStorage.removeItem('test');  // delete the item

In setItem, getItem and removeItem the first argument is the key that you want to store or retrieve or delete from the storage. The name of the key in this case is test.

like image 91
Sushanth -- Avatar answered Feb 02 '23 17:02

Sushanth --