This code has been checked for errors and none were detected. But, when it runs, it alerts null.
For Sololearners my code bit: https://code.sololearn.com/WOv1cF0EewdB/?ref=app
Why is this?*
JavaScript
x
47
47
1
window.onload = function() {
2
3
let reload_interval= setInterval(rel, 120000);
4
5
if (localStorage.getItem('visit') !== true) {
6
7
8
let username = prompt('Enter your name:');
9
10
if (confirm('Do you want to be known as ' + username + ' from now on?')) {
11
12
localStorage.setItem('name', username);
13
14
} else {
15
16
username = prompt('OK then, enter your name:');
17
18
if (confirm('Do you want to be known as ' + username + 'from now on?')) {
19
20
localStorage.setItem('name', username);
21
22
}
23
24
}
25
26
localStorage.setItem('visit', true);
27
28
}
29
30
if (localStorage.getItem('visit') === true) {
31
32
document.getElementById('p').innerHTML = localStorage.getItem('name');
33
34
alert('Hello, ' + localStorage.getItem('name'));
35
36
}
37
38
39
};
40
41
function clearLocalStorage() {
42
if (confirm('Do you want to clear current username data?')) {
43
localStorage.clear();
44
alert('Cleared');
45
}
46
}
47
*jQuery answers are OK
Advertisement
Answer
You are not getting a hello alert is because you are checking getItem
‘s return value with === true
and !== true
.
setItem
will convert your value to string
, so localStorage.getItem('visit') === true
will never be true
If you want to check if the user has visited the page, you should use === "true"
(visited) and !== "true"
(not visited) since it returns string
.