1

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

1
  • I would recommend to you, using jquery .... Commented Dec 17, 2014 at 21:02

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.