Zizi
Zizi

Reputation: 11

JS - Confusion between string and int variables

Javascript is really bugging my head. At first I was using this code :

var val = document.getElementById("inputField").value; // User entered "2"
while (val < 5)
{
    val += 1
    alert(val);
}

But it would do 5+1 = 51 unless I use parseInt before entering the while loop. So that means that val is Not a Number. But however it has no problem considering val as a number upon entering the while loop, in the expression(val < 5). Why is it so ? It looks illogical to me, unless you tell me that "that's the way it is". Ty

Upvotes: 1

Views: 146

Answers (1)

Muhammad Gouda
Muhammad Gouda

Reputation: 869

It is obvious in programming world that var x = 5 differs from var x = "5" As the former undersands 5 as a number while the later understands 5 as a character or a string of one charcter

The problem here comes from 2 sources

Number 1: Is that the numeric value is obtained from the html control input that accepts literal text in its value property (even if it was of type number)

Number 2: Is that "+" operator accepts both numeric and text operands. where 5 + 1 result in 6. While "5" + "1" result in "51". Also "5"+1 results in "51"

So, javascript sees entered value is a valid as text and number and plus operations work with both types so, it handled it as a text as there is no other sign indicate it is a number

If you replace '+' with '*' which does not accept text as operands, you will get the expected result where "5" * 5 = 25

Here jS tried to apply multiplication on text as a number and it succeded But if the text was not parsaple as a number. say "x", then "x" * 5 will result to NaN

Upvotes: 1

Related Questions