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.
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.
Share Improve this question asked Jul 11, 2017 at 22:17 JepiJepi 971 gold badge1 silver badge9 bronze badges 3-
4
Just remove it with quotes like
localStorage.removeItem("test");
also check developer.mozilla/nl/docs/Web/API/Window/localStorage – Hakan Kose Commented Jul 11, 2017 at 22:23 - Oh, It's work, it's help me, thanks Hakan Kose – Jepi Commented Jul 11, 2017 at 22:26
- Errors like this are a good reason to learn about and get into the habit of using Strict Mode JavaScript (specially browser implementations of JavaScript) have some wild methods of resolving global variables – Jason Sperske Commented Jul 11, 2017 at 22:26
1 Answer
Reset to default 11The 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 e 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
.