Lumpy79
Lumpy79

Reputation: 25

In JavaScript why Number() function does not work here and gives back a string?

I have this simple example and can not figure out the solution. Can somebody please tell me why n is still a string after used the Number() function? Thanks!

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Still a string</title>
<style>
  input {
    width: 30px;
  }
</style>
</head>
<body> 
    n = <input type="number" id="n"><br/>

    <button id="but" onclick="gen()">Push me!</button>

    <script>
        var n;
        function gen() {
        n = document.getElementById("n").value;
        Number(n);
        alert(typeof n);
        }
    </script>
</body>
</html>

Upvotes: 1

Views: 55

Answers (2)

Ajay Gaur
Ajay Gaur

Reputation: 5270

The primitive data types (Strings, numbers, boolean etc.) in javascript are immutable

So, whenever you change String "n" to number, a number is stored on memory but "n" is still referring to the same String.

Instead you should type your code as:

var n;
function gen() {
    n = document.getElementById("n").value;
    n = Number(n);
    alert(typeof n);
}

Upvotes: 1

madox2
madox2

Reputation: 51851

Number does not convert parameter to number but returns number, try this:

function gen() {
    var n = document.getElementById('n').value;
    var num = Number(n);
    alert(typeof num);
}

Upvotes: 2

Related Questions