SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Thread: Double tilde?

  1. #1
    SitePoint Addict sdleihssirhc's Avatar
    Join Date
    Feb 2009
    Posts
    387
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Double tilde?

    I see some scripts put two tildes in front of variables, like so:

    Code:
    var a = ~~b;
    As far as I can tell, all this does is ensure that a is given a number value. But is there a reason to prefer ~~ over +?

    Code:
    var a = +b;
    Or is there something else going on?

  2. #2
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,061
    Mentioned
    153 Post(s)
    Tagged
    2 Thread(s)
    Never knew that one.
    Looked it up, and it does -(N+1)

    So, if you have 1 ~~"2", you get the following:

    Code:
    -(-(2+1)+1) =
    -(-(3)+1) =
    -(-2) =
    2
    Read this article. It points out that is handy to handle sentinel values.

  3. #3
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,807
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    ~ actually does a 2s complement on the individual bits. In any language except JavaScript doing bit operations like that would be a billion times faster than doing arithmetic operations. JavaScript is extremely slow at bit operations so any other way would probably be faster than using bit operators (which is why you don't often see them used in JavaScript). Generally only programming gurus who are also JavaScript newbies would consider them.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  4. #4
    SitePoint Wizard Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,276
    Mentioned
    50 Post(s)
    Tagged
    2 Thread(s)
    Wow, bookmarked.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •