Negation of zero results in an error

I'm having a problem: negating zero results in an error in my JavaScript code. I have simplified the code to demonstrate the problem as indicated below.

<input id="iid" value="0" />

<script type="text/javascript">
  zero = document.getElementById('iid').value;  
  alert( ( !zero ? 'true' : 'false' ) );  // alert message is "false".
</script>

      

Why does the negation of zero become false?

+3


source to share


4 answers


You are negating the string "0"

. Any line becomes false

on negation, except for an empty line:

!0       true
!"0"     false
!""      true
!+"0"    true

      



The last expression true

, because the operator +

converts the string to a number.

The input value is always a string, which also makes sense semantically because it is a combination of characters entered by the user. If you want to interpret this number, you will have to convert it to one.

+1


source


The string "0"

is equal to " true

", negating it false

.

If you want a number, you have to parse it:



var valueAsNumber = parseInt(document.getElementById('iid').value, 10); 

      

+4


source


Because it is not a number zero, it is a string with a "0" in it. All non-empty strings, no matter what characters they contain, are true

treated as booleans.

+1


source


try doing it like this:

<input id="iid" value="0" />

<script type="text/javascript">
  zero = Number(document.getElementById('iid').value);  
  alert( ( !zero ? 'true' : 'false' ) );
</script>

      

+1


source







All Articles