Sunday, March 24, 2013

JavaScript: The less known parts. Bitwise Operators.

'JavaScript: The less known parts' chapters:
1. Bitwise Operators
2. Storage
3. Dom Mutations

Most of us probably use JavaScript every day - in my case it's building a mobile operating system in my daily job, preparing crazy and ridiculous demos for various conferences or run personal projects in my free time (mostly games). But even with years of experience (probably because the language itself is full of weird quirks and unintuitive patterns), from time to time I'm still getting surprised with new crazy hacks, techniques or workarounds. I want to put most of those things in one place and publish one every Monday - for last couple of years I wasn't really active on the blog, it's time to change this. First - bitwise hacking.

Bitwise operators

Most of us know know that there are some bitwise operators in JS. Every number has it's own binary representation, used by those operators. To check dec number's binary value, we use .toString() method with base argument - '2' for binary:

There are seven different bitwise operators. Assuming that variable a is equal to 5, and b is 13, those are actions and results of their operations:

Sometime we even use Bitwise OR as equivalent of Math.floor():

It has the same effect as double NOT operator (my favorite rounding solution since I first heard about it on Damian Wielgosik's workshop couple of years ago).

What about other real life examples of bit chaking? For instance, we can convert colors from RGA to Hex format:

We can also simply check which number in a pair is smaller (like Math.min) or bigger (Math.max):

Of course since Math library is really well optimized nowadays, using those hacks doesn't make any sense. But what about variables swap? Most common solution is to create a temporary variable to achieve that, what is not really efficient. It's simpler to use bit operations here:

Even with 'Pythonish' variable swap introduced in JavaScript 1.7, bitwise solution is the fastest way to achieve that.
JSPerf test [here]:

Great place to learn more bit-tricks to make your JS app: Sean Eron Anderson's site [Stanford PhD].
Do you know and use any more binary tricks in your JavaScript projects?


  1. Cool overview!

    I would like to point out that the delete operation in the 'temp variable' JSPerf case is what's slowing it down. The delete operation isn't valid anyway -- it won't succeed in function context and will return false.

    1. Can we see another JSPerf test without the delete line?

    2. It's already there, in revisions of original test.

  2. I still use a << 1 and a >> 1 as a shortcut for Math.floor( a * 2 ) and Math.floor( a / 2 );

    1. You can use 1 >> a as a shortcut for Math.pow(2, a)

    2. i'm trying this in chrome devtools but it doesn't seem to work. the result is always 0.

  3. Temporary variable method seems to be faster on Chrome. And V8 doesn't recognize the JS 1.7 method.

    1. Of course, but anyway, temp var method in Chrome is almost twice slower than bitwise swapping in Firefox. And this method works only for integers, so I don't expect everyone to use it now, I just wanted to show that it's possible.

    2. You can use !! for booleans (or perhaps Boolean()), although I'm not sure how quick it will be.

  4. As Anonymous above said you should verify your final results with other browsers. Especially with Chrome.

  5. Unless only gurus are expected to read the article, you should also mention that this works mostly for integer values (except the flooring with shifting or OR).

  6. This article shows us interesting curiosities, which meant performance improvements some years ago. And I'm sure it still means performance improvements for JS being interpreted by powerful Internet Explorer JS engines.

    Concerning this binary variable exchange:
    We can extend the integer exchange without temporary variable to all numbers (representable with the available precision) with this commonly taught short operations:

    a += b;
    b = a-b;
    a -= b;

    and this is actually slower than previous binary operations, and even more slower than temporary variable usage.

    Concerning another use case for binary operations being faster than commonly used operator: checking if an integer i is a multiple of the integer b which is a power of 2.

    The test is:

    var amount = 1e4, i, b=32;


    i = amount;
    while(i--) { i%b }




    i = amount;
    while(i--) { i&c }


    And the times I get on Chrome:
    %: 37.000ms
    &: 19.000ms

    However, setting the iteration amount to 1e5 is removing this time difference. And the reason is ?

    1. I meant "i&b" instead of "i&c".

  7. var arr = [1,2,3];
    ~arr.indexOf(2); // => 1
    ~arr.indexOf(4); // => 0

    one's complement in base 10 turns -1 to 0 and all other numbers to not -1

  8. Umm...I meant -1 to 0 and all other numbers to not 0

    ~x will coerce to false when x === -1
    ~x and to true otherwise

  9. In the reg2hex function, I did not get the point for doing (1 << 24) and then doing substr(1). Why is it done?
    The above code is working without these two components too (atleast for the case of #BADA55 color)

  10. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! Its always nice when you can not only be informed, but also entertained! Im sure you had fun writing this article.
    Microsoft dynamics training

  11. Fantastic article ! You havemade some very astute statements and I appreciate the the effort you have put into your writing. Its clear that you know what you are writing about. I am excited to read more of your sites content.

    Latest jobs

  12. I can see that you are are genuinely passionate about this! great information.
    thank you...!
    Hadoop training

  13. hi...Im student from Informatics engineering nice article,
    thanks for sharing :)

    Work from home theory is fast gaining popularity because of the freedom and flexibility that comes with it. Since one is not bound by fixed working hours, they can schedule their work at the time when they feel most productive and convenient to them. Women & Men benefit a lot from this concept of work since they can balance their home and work perfectly. People mostly find that in this situation, their productivity is higher and stress levels lower. Those who like isolation and a tranquil work environment also tend to prefer this way of working. Today, with the kind of communication networks available, millions of people worldwide are considering this option.

    Women & Men who want to be independent but cannot afford to leave their responsibilities at home aside will benefit a lot from this concept of work. It makes it easier to maintain a healthy balance between home and work. The family doesn't get neglected and you can get your work done too. You can thus effectively juggle home responsibilities with your career. Working from home is definitely a viable option but it also needs a lot of hard work and discipline. You have to make a time schedule for yourself and stick to it. There will be a time frame of course for any job you take up and you have to fulfill that project within that time frame.

    There are many things that can be done working from home. A few of them is listed below that will give you a general idea about the benefits of this concept.

    This is the most common and highly preferred job that Women & Men like doing. Since in today's competitive world both the parents have to work they need a secure place to leave behind their children who will take care of them and parents can also relax without being worried all the time. In this job you don't require any degree or qualifications. You only have to know how to take care of children. Parents are happy to pay handsome salary and you can also earn a lot without putting too much of an effort.

    For those who have a garden or an open space at your disposal and are also interested in gardening can go for this method of earning money. If given proper time and efforts nursery business can flourish very well and you will earn handsomely. But just as all jobs establishing it will be a bit difficult but the end results are outstanding.

    Freelance can be in different wings. Either you can be a freelance reporter or a freelance photographer. You can also do designing or be in the advertising field doing project on your own. Being independent and working independently will depend on your field of work and the availability of its worth in the market. If you like doing jewellery designing you can do that at home totally independently. You can also work on freelancing as a marketing executive working from home. Wanna know more, email us on and we will send you information on how you can actually work as a marketing freelancer.

    Internet related work
    This is a very vast field and here sky is the limit. All you need is a computer and Internet facility. Whatever field you are into work at home is perfect match in the software field. You can match your time according to your convenience and complete whatever projects you get. To learn more about how to work from home, contact us today on workfromhome.otr214423@gmail.comand our team will get you started on some excellent work from home projects.

    Diet food
    Since now a days Women & Men are more conscious of the food that they eat hence they prefer to have homemade low cal food and if you can start supplying low cal food to various offices then it will be a very good source of income and not too much of efforts. You can hire a few ladies who will help you out and this can be a good business.

    Thus think over this concept and go ahead.

  15. This is very informative blog and i will share this blog.I have also created this blog for client side and server side scripting.Learn and create your first web app with angularjs.Here i have provided the very easy tutorial for this.

    Learn AngularJs from scratch

  16. I time to time see some people using bitwise operators in the place of Math.floor(). I think this is totally unnecessary and better be avoided for the following reasons;
    1) Both are running almost at the same speed in all modern JS engines.
    2) They behave differently when the operant is a negative number. Such as ~~-2.14; // -2 however Math.floor(-2.14); // -3
    3) Making your code less readable and understandable won't make you any cooler coder.

  17. Thank you so much for sharing this worthwhile to spent time on. You are running a really awesome blog. Keep up this good work Hadoop training institutes in chennai

  18. Hello , I have been training students on AngularJS for past 6 months, and at times, I have used your blog as reference for the class training and also for my personal project development. It has been so much useful. Thank you, keep writing more:)
    AngularJS courses in Chennai

  19. Thank you for the information , I wait for more information and I ask for a return visit our new website
    >> Obat pembesar penis <<

  20. Hello , I have been training students on AngularJS for past 6 months, and at times, I have used your blog as reference for the class training and also for my personal project development. It has been so much useful. Thank you, keep writing more:)
    AngularJS training

  21. There are lots of information about latest technology and how to get trained in them, like Best Hadoop Training In Chennai in Chennai have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies Hadoop Training in Chennai By the way you are running a great blog. Thanks for sharing this blogs..

  22. I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
    SalesForce Training in Chennai

  23. Pretty article! I found some useful information in your blog, it was awesome to read,thanks for sharing this great content to my vision, keep sharing..
    Unix Training In Chennai

  24. This information is impressive..I am inspired with your post writing style & how continuously you describe this topic. After reading your post,thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..
    Android Training In Chennai In Chennai

  25. SAP Training in Chennai
    This post is really nice and informative. The explanation given is really comprehensive and informative..

  26. Oracle Training in chennai
    Thanks for sharing such a great information..Its really nice and informative..

  27. Selenium Training in Chennai
    Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

  28. Data warehousing Training in Chennai
    I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly..

  29. Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing..
    Websphere Training in Chennai

  30. Oracle DBA Training in Chennai
    Thanks for sharing this informative blog. I did Oracle DBA Certification in Greens Technology at Adyar. This is really useful for me to make a bright career..

  31. This is really an awesome article. Thank you for sharing this.It is worth reading for everyone. Visit us:
    Oracle Training in Chennai

  32. very nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.
    Oracle DBA Training in Chennai

  33. great article!!!!!This is very importent information for us.I like all content and information.I have read it.You know more about this please visit again.
    Oracle RAC Training in Chennai

  34. Wonderful tips, very helpful well explained. Your post is definitely incredible. I will refer this to my friend.
    SalesForce Training in Chennai

  35. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.
    Java Training in Chennai

  36. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    PHP Training in Chennai

  37. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me..
    Android Training in Chennai

  38. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
    SAP Training in Chennai

  39. Excellent information with unique content and it is very useful to know about the information based on blogs.
    Hadoop Training in Chennai