If you try to read a key for which no
data has been written, the result will
be null
. This can be used to
perform a one-time data save.
For example, let's write to the local storage the moment the user first visits the site. And if the user doesn't log in for the first time, then we will do nothing:
let time = localStorage.getItem('time');
if (time === null) {
let now = Date.now();
localStorage.setItem('time', now);
}
Let us rewrite the condition in a shorter form:
let time = localStorage.getItem('time');
if (!time) {
let now = Date.now();
localStorage.setItem('time', now);
}
When a user enters the site, write the current time to the local storage. Then, on the second visit, output how much time has passed since the user's previous visit to the site.
When a user enters the site, ask him for his date of birth. The next time a user visits the site, if he has a birthday that day, congratulate him with it.
An input is given. When focus is lost on this input, save its value in local storage. The next time the user enters the page, set the previously saved text in the input.