0

In the below code, the if statement always fails. New to JavaScript, couldn't figure out.

I believe the code is self explanatory. What am I doing wrong?

if (localStorage.user_name === null || localStorage.user_name === 'undefined') {
    registerUser(userName);
} else {
    login(localStorage.user_name);  // Gets executed always... Even if there is no user_name in localStorage.
}
Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126

1 Answers1

1

The problem is in your second condition. Since you're using ===, and comparing with 'undefined' which is a string, instead of undefined, it returns false. So, you need localStorage === undefined, as in

if (localStorage.user_name === null || localStorage.user_name === undefined)

Or, need to use typeof which returns String. But there's a better way

if(!localStorage.user_name){

}
Amit Joki
  • 58,320
  • 7
  • 77
  • 95