Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my variable is true and not true at the same time?

Tags:

javascript

Just take a look at this javascript:

localStorage.myAwesomeItem = true;
var item = localStorage.myAwesomeItem;
alert(item);
if(item==true)
    {alert("really true");}
else
    {alert("lies; not true");}

jsfiddle

I set myAwesomeItem of the local storage to true. Fine. Then I store this item in a variable called item. And alert to check its value. As you see, it is true.

Then I check through the condition if my item is really true. But it is not. It goes for the else.

Can anyone explain me this behavior?

like image 467
nicael Avatar asked Dec 15 '22 15:12

nicael


2 Answers

Local storage converts anything stored in into string. So you can get it working by doing this:

if(item=="true")...
like image 141
lalitpatadiya Avatar answered Jan 07 '23 15:01

lalitpatadiya


Localstorage stores everything as strings. So the true you input is actually saved as "true" and the false as "false".

All non-empty strings in javascript evaluate to true.

like image 44
EasyPush Avatar answered Jan 07 '23 15:01

EasyPush