0

In Firefox 45 on OSX, when I fetch an item from localStorage from a key that does not exist, the function call returns null. I tested this in the console.

If I instead assign the call result to a variable, and print its value in the console, I get "null", i.e. a string.

Why does a variable assignment of a previously not defined variable cast a call result to a String?

Used code (in the console):

localStorage.getItem("non-existing-key"); // returns null

var x = localStorage.getItem("non-existing-key");
x // returns "null"

Edit: both versions seem to behave correctly on Chrome 50.0.2661.86 on OSX (both return null)

Edit2: my mistake. I used another variable name in my tests (specifically: var name). Now, if I let the console return the value of the variable name, it returns window.name, which is a property of window of the type String, defaulting to "null". So, it's not an assignment that causes a cast, but instead its that I got a String property defined by window.

Lukas_Skywalker
  • 2,053
  • 1
  • 16
  • 28
  • firefox 45.0.2 on windows, cannot reproduce: localStorage.getItem("non-existing-key"); // returns null var x = localStorage.getItem("non-existing-key"); x // --> returns null not "null" – Giuseppe Apr 25 '16 at 08:01
  • What does it return in other browser ? I reckon you are confused between `null` and `"null"` – Rayon Apr 25 '16 at 08:06
  • Both versions behave the same on Chrome 50 on OSX by returning `null`, but I had at least one instance where Firefox 45 on Win7 returned "null" as String after the assignment yesterday. – Lukas_Skywalker Apr 25 '16 at 08:10

1 Answers1

0

I made a mistake. The specific code I used was the following:

var name = localStorage.getItem("non-existing-key");
name

Now, getItem does return null and not a String. What then happens is that by letting the console print the value of name it does in fact get window.name (see window.name on MDN), which by default is "null" (a String).

Lukas_Skywalker
  • 2,053
  • 1
  • 16
  • 28