Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why localStorage return a string value with case null and undefined [duplicate]

When I save a null/undefined value into localStorage. The result I recieved when use localStorage.getItem will be a string ("null" or "undefined")

localStorage.setItem("item1", null)
localStorage.setItem("item2", undefined)

const item1 = localStorage.getItem("item1")
const item2 = localStorage.getItem("item2")

console.log(item1) // The result will be "null" not null
console.log(item2) // The result will be "undefined" not undefined

Anyone can explain for me with this case !

like image 713
aldenn Avatar asked Oct 16 '25 13:10

aldenn


1 Answers

Js does Stringify it to local storage

storage.setItem(keyName, keyValue)

keyName and KeyValue both are of type DOMString

DOMString is a UTF-16 string. As JavaScript already uses such strings, DOMString is mapped directly to a String.

Passing null to a method or parameter accepting a DOMString typically stringifies to "null"

I saw we have 2 answers at the same time, so just to add his part from mdn docs and for DOMString

like image 147
Shreyan Mehta Avatar answered Oct 18 '25 06:10

Shreyan Mehta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!