0

i am creating a website that remembers your name and welcomes you back the second time you reload the page. I am storing the data in the localStorage because its better than cookies and its never expires, thank you for your consideration!

var person = prompt("please enter your name","you are...");
var person1 = +localStorage.getItem("person1");

if(person1 == null){
  alert(person);
  localStorage.setItem("person1");
}
if(person1 != null){
 alert("welcome back " + person + "!"); 
}
Daniel Underwood
  • 2,191
  • 2
  • 22
  • 48
  • Why do you have a `+` before the localStorage? Where do you see setItem with one parameter? [Documentation shows two.](https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem) – epascarello Jan 05 '17 at 01:54

1 Answers1

2

Well for one, person is always going to be prompted since you aren't checking localStorage.getItem before prompting. Second, you aren't actually setting anything with localStorage.setItem since you don't give a second argument.

You may want something like the following:

var username = localStorage.getItem("username");
if(!username){
    username = prompt("Please enter username");
    localStorage.setItem("username", username);
}

Be aware that like in your usage of setItem, JavaScript will not warn you or have an error if arguments are not supplied to a function call. Be sure to check that you're actually passing what is necessary.

You'll also want to note that not all browsers will support localStorage. You may want to read up on some questions such as this one to look at some of the other differences between localStorage and cookies. One of the big ones is that localStorage is client-side while cookies are server-side.

Community
  • 1
  • 1
Daniel Underwood
  • 2,191
  • 2
  • 22
  • 48
  • Thank you Daniel! I'm kinda a moderate beginner if that makes sense to javascript, my first year of programming was mostly HTML and CSS and this is only my seccond year. But thank you again for helping out people like me! – Liam Sperry Jan 05 '17 at 11:33