Reputation: 25
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
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
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