You can think of localStorage
as a persistent object associated with a domain.
Whaaat…
Okay, look, it’s an object.
An object is a thing that has properties and values, right?
So we can create an object and name it word
:
let word = {}
But that’s empty. We can assign a property and a value to that object, using either “dot notation” or “bracket notation”. They’re mostly the same thing.
word.form = "casa" word["gloss"] = "house"
Is word an object?
typeof word // object
Yep.
We can get the values of properties back in the same way:
word.form // "casa"
Notice that quotes — that’s Javascript saying “the value of word is a string”.
We could add a non-string value, like this:
word.letterCount = 4
If we ask Javascript what word.letterCount
is, there will be no quotes:
word.letterCount // 4
We could even ask what type that value is:
typeof word.letterCount // "number"
Hey, it’s a number!
Watch:
4 + 2 // 6 "4" + "2" // "42"
Wait, what? Well, it’s just like saying:
"a" + "b" // "ab"
That’s JS saying “oh, you want me to add this string and that string? Fine. I’ll stick them together.
If you add numbers, it knows to do math.
Wait, localStorage
.
So anyway, you can properties and values to objects like we did with word
.
It so happens that there is an object called localStorage
which is always there. Like that kid who had a crush on you in the second grade, it never ever goes away.
Sort of. Try typing this in your console:
localStorage
You will see something different from what I see. But it will also change for you, depending on what domain you are on. I just found a random website called the Montana Organic Association”. I guarantee you I have never been there before. If I go into the console on that site, and type localStorage
, what do I see? (And you will probably see too, unless you are… in Montana… and into organic farming…)
localStorage // you’ll see something like: // Storage { length: 0 }
Forget the details, that means that localStorage
is empty.
But you can add something.
localStorage.wahoo = "rutabegas forever!"
Now, if you ask the console what is in localStorage
, you will see:
Storage { wahoo: "rutabegas forever!", length: 1 }
You can also you use the bracket notation, like any object, by the way:
localStorage["hooray"] = "arugala revolution"
And now localStorage
is an object that contains both of those.
But, if you go to some other website, (why am I picking organic farming websites??), like this one, now your localStorage.wahoo
and localStorage.hooray
are gone.
That’s because every single domain gets its own localStorage
object.