0

I'm still a newbie developer and would really appreciate some help. The below function on() is called from within another function when the user scores 10/10 on a quiz. The username is initially created from a username login on a different page and that value is successfully stored in localStorage. That part is working fine and I can call that value (within the on() function) using the first part of the below statement if I leave out the first 'if' statement line and the entire 'else if' statement. However, I'm trying to cater for the time should the user not enter a username, because when the first part of the on() function is called it displays the following: "Congratulations {null}! You scored the perfect 10". I would prefer it to display the alternate message within the 'else if' section below. Any guidance on what I'm doing wrong would be appreciated.

function on() {
    if (localStorage.getItem("users") == true) {
    document.getElementById("overlay").style.display = "block";
    document.getElementById("overlay").innerText = "Congratulations " +
    window.localStorage.getItem('users') + "! You scored the perfect 10!";
    } else 
    if (localStorage.getItem("users") === null) {
    document.getElementById("overlay").style.display = "block";
    document.getElementById("overlay").innerText = "Congratulations! You scored the perfect 10!";
}
Harry
  • 4,660
  • 7
  • 37
  • 65
  • 1
    Can you share what is being stored in the localStorage? – Safir Motiwala Sep 06 '21 at 07:18
  • Your indentation is confusing, but if I add the final `}` and indent properly I get code that looks more or less fine and [works as expected](https://jsfiddle.net/7qg3p0rc/). The problem I guess is that you're storing a string in localStorage, so your check should look like this: `if (localStorage.getItem("users"))` (you can omit `!== null` from the check) And you only need an `else`, you don't need to compare the entire thing against null again. –  Sep 06 '21 at 07:23
  • https://stackoverflow.com/questions/3262605/how-to-check-whether-a-storage-item-is-set – AL.Sharie Sep 06 '21 at 07:23
  • Sorry, how do I add further code? – commandoChicken Sep 06 '21 at 07:26
  • @ChrisG - I added the extra bracket, but it doesn't display the alternate message. – commandoChicken Sep 06 '21 at 07:33
  • That curly brace will make or break your syntax; please always check the browser console for errors (press F12). Did you change the test like my code suggested? I.e. use just `if (localStorage.getItem("users"))` and `else`? Here's a rewritten version: https://jsfiddle.net/hqj5d2mL/ with muss less duplicate code. –  Sep 06 '21 at 07:35
  • @ChrisG - you're a genius! I adjusted my if statement and took out the 'null' portion and it works well. Thank you very much – commandoChicken Sep 06 '21 at 07:41
  • Thanks, but that's really basic stuff ;) –  Sep 06 '21 at 07:45

0 Answers0