The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
> Comparison with 0 and JSLint error
RainLover
post Jul 11 2014, 02:38 AM
Post #1


Advanced Member
****

Group: Members
Posts: 216
Joined: 16-November 09
Member No.: 10,346



Here's the code:

CODE
<input type="number" value="0" id="input">
<script>
  if (document.getElementById('input').value == 0) {
    alert('Hello, world!');
  }
</script>


DEMO

And here's the JSLint error:

QUOTE
Expected '===' and instead saw '=='.


But when I listen to the advice and change == to ===, the alert stops appearing.

This post has been edited by RainLover: Jul 11 2014, 02:39 AM
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Jul 11 2014, 04:34 AM
Post #2


.
********

Group: WDG Moderators
Posts: 9,630
Joined: 10-August 06
Member No.: 7



The === operator compares both value and type, but IIRC the type of a form field value is always "string". This means that:

CODE
if (document.getElementById('input').value === 0)

can never be true, since it checks for the number zero. Instead, try using quotes:

CODE
if (document.getElementById('input').value === '0')

which makes it into a string with the value zero.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
RainLover
post Jul 11 2014, 04:41 AM
Post #3


Advanced Member
****

Group: Members
Posts: 216
Joined: 16-November 09
Member No.: 10,346



QUOTE(Christian J @ Jul 11 2014, 04:34 AM) *

the type of a form field value is always "string".

That's what I wanted to make sure about. Thanks! smile.gif

Am I right in my assumption that input.value == '0' is faster than input.value == 0 as the first one doesn't need a conversion?

This post has been edited by RainLover: Jul 11 2014, 05:27 AM
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Jul 11 2014, 06:51 AM
Post #4


.
********

Group: WDG Moderators
Posts: 9,630
Joined: 10-August 06
Member No.: 7



QUOTE(RainLover @ Jul 11 2014, 11:41 AM) *

QUOTE(Christian J @ Jul 11 2014, 04:34 AM) *

the type of a form field value is always "string".

That's what I wanted to make sure about. Thanks! smile.gif

Can't remember any spec reference for it (despite discussing it here in several older threads), but you can test browsers with

CODE
alert(typeof formfield);


QUOTE
Am I right in my assumption that input.value == '0' is faster than input.value == 0 as the first one doesn't need a conversion?

No idea, why not do a test on a large number of INPUT elements? For inspiration, here's another javascript speed test: http://quirksmode.org/dom/innerhtml.html

User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 



- Lo-Fi Version Time is now: 29th March 2024 - 03:09 AM