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?
source to share
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.
source to share