Javascript Tip: ‘Number()’ function

June 11, 2008

Context:

Trying to do a simple number comparison, can be surprising in javascript sometimes. For example…

function fooMethod( fooVariable )
{
    if ( fooVariable > 10 )
    {
        alert('true');
    }
    else
    {
        alert('false');
    }
}

… where fooVariable is a number taken from a form, and hence originally of type string ! Sometimes feeding in the number “5″ may end up evaluating as true… even though it should be false ( 5 > 10 ) !

Solution:

The problem is to do with Javascript being weakly-typed, hence although 5 is smaller than 10, it may be treated as the string 5 rather than than the number 5. The solution is to make use of the convenient ‘Number‘ function provided by javascript (part of the core library). As follows…

function fooMethod( fooVariable )
{
    if ( Number( fooVariable ) > 10 )
    {
        alert('true');
    }
    else
    {
        alert('false');
    }
}

… that’ll ensure that if not already a number type it is converted before the comparison is made. Very nice !

Wa Allahu A’lam

Entry Filed under: Javascript. Tags: , , , .

4 Comments Add your own

  • 1. drj11  |  June 11, 2008 at 4:17 pm

    “+fooVariable” also works, as in:

    if(+fooVariable > 10)

    Reply
  • 2. Ibn Aziz  |  June 11, 2008 at 4:29 pm

    Thanks for the comment drj11… but as far as I know (please correct me if I am wrong)… using the ‘Number()’ function has other benefits such as returning a ‘NaN’ if the original input is NOT a number at all… is the same true for the operator ‘+’… ?

    Reply
  • 3. drj11  |  June 11, 2008 at 6:51 pm

    They are identical in behaviour. As per the standard.

    js> +’0×10′
    16
    js> +’foo’
    NaN

    Reply
  • 4. Ibn Aziz  |  June 11, 2008 at 8:17 pm

    Ok.. that’s nice. Thanks for the update…

    Reply

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent Posts

Recent Comments

Categories

Top Posts

Links

Blog Stats

Meta