Search code examples
javascripttype-conversionparseint

Why does parseInt() sometimes return a string?


This is a direct copy/paste from the javascript console on a new tab in chrome:

> var name = parseInt(prompt("enter a number"), 10);
undefined
> name
"77"
> var x = parseInt(prompt("Enter a number"), 10);
undefined
> x
77

For some reason this only seems to happen if I use the variable name "name". It stays a string even on a regular assignment:

>name
"453"
>name = 77;
77
>name
"77"

Solution

  • The global variable name is a special variable in browsers which represents the name of the current window and is always a string.

    As a rule of thumb, it is generally a good idea to wrap scripts in an IIFE so they have a local scope and you don't get conflicts with variables from other scripts and the browser. Doing so would avoid this issue.