Mohammed H
Mohammed H

Reputation: 7048

Negation of zero produces false

I got an issue that negation of zero produces false in my JavaScript code. I have simplified the code to demo the issue as given 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 negation of zero become false?

Upvotes: 3

Views: 723

Answers (4)

Jord&#227;o
Jord&#227;o

Reputation: 56467

The string "0" is "true", negating it is false.

If you want a number, you should parse it:

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

Upvotes: 4

Tom
Tom

Reputation: 4180

try it like this:

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

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

Upvotes: 1

pimvdb
pimvdb

Reputation: 154818

You're negating the string "0". Any string becomes false when negated except the empty string:

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

The last expression is true because the + operator converts the string into a number.

An input value is always a string, which makes sense semantically as well because it's a combination of characters entered by the user. If you want to interpret is as a number you'll have to convert it into one yourself.

Upvotes: 1

Pointy
Pointy

Reputation: 413712

Because that's not the number zero, it's a string with the character "0" in it. All non-empty strings, regardless of what characters are in them, are true when treated as booleans.

Upvotes: 1

Related Questions