0

I am coming from Java dev and new to javascript, can someone explains what is going on.

I am using localStorage to store my token in my browser.

localStorage.token = 'xxx'

When the users sign out, we remove the token, here is the code

localStorage.token = null

If we want to check wether the user is authenticated or not, we check the token

const isAuth = localStorage.token !== null

Here is the thing becomes weird to me. After I marked localStorage.token to null,

the result of localStorage.token !== null is still true !


I had done some investigation,

I logged the localStorage object and found out the token variable is "null" instead of null.

Here is my assumption.

When the browser needs to store the localStorage, it iterates inside the object fields, after finding the null object, it use toString to store the final form?

1
  • 1
    There are built in JS function to achieve what you want. First you can use removeItem() to delete it from localstorage. If you use the function getItem(), it will give you an null on return! Commented Jun 1, 2022 at 11:29

5 Answers 5

1

Localstorage in the browsers work only on the string types

localStorage.getItem('someItem');
localStorage.setItem('someItem', 'string value');
localStorage.removeItem('someItem');
Sign up to request clarification or add additional context in comments.

Comments

1

give a value or overwrite the one present in the localstorage with the function set item, like code below :

localStorage.setItem('token' , 'your token here ');

and for access the value :

localStorage.getItem('token')
window.console.log("token :",localStorage.getItem('token'))

Comments

0

Use localStorage methods for setting, getting and removing token.

Check this link for more details: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

And for checking weather the token exists or not you can do this:

const isAuth = !!localStorage.token

Comments

0

You can use removeItem() to remove items from your localstorage.

localStorage.removeItem('token')

You can also use the function getItem() to retrieve the item.

localStorage.getItem('token')

This will return null when it doesn't exist.

Documentation

https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem

https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem

https://blog.logrocket.com/localstorage-javascript-complete-guide/

Comments

0

Local storage can only save strings. That is a simple fact of life. This is why JSON.parse and JSON.stringify are synonymous with reading and writing from and to local storage. null is no exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.