#vanilla javascript
Glad Chinda
Apr 13, 2023 ⋅ 15 min read

A guide to JavaScript bitwise operators

Glad Chinda Full-stack web developer learning new hacks one day at a time. Web technology enthusiast. Hacking stuffs @theflutterwave.

Recent posts:

Implementing In App Updates For React Native Apps

Implementing in-app updates for React Native apps

Implementing OTA in-app updates in React Native apps can streamline the update process, preventing delays that hinder overall productivity.

Nelson Michael
Mar 1, 2024 ⋅ 7 min read
Exploring Stylex And The New Generation Of Styling Libraries

Exploring StyleX and the new generation of styling libraries

StyleX is a build-time, type-safe CSS-in-JS library recently open sourced by Meta. Explore StyleX and the evolution of styling libraries.

Ibadehin Mojeed
Feb 29, 2024 ⋅ 9 min read
Building High Performance Ecommerce Sites With Astro

Building high-performance ecommerce sites with Astro

Learn to set up a completely custom Astro ecommerce implementation that’s also highly performant and type-safe in this straightforward guide.

Onuorah Bonaventure
Feb 28, 2024 ⋅ 64 min read
Implementing Vector Search With Open Ai, Next Js, And Supabase

Implementing vector search with OpenAI, Next.js, and Supabase

Let’s build a Next.js app that implements vector search using Supabase and OpenAI to offer better search experiences for users.

Peter Ekene Eze
Feb 27, 2024 ⋅ 11 min read
View all posts

8 Replies to "A guide to JavaScript bitwise operators"

  1. There’s a very handy trick that uses the & operator but has nothing to do with bitwise operations.
    Let’s say you have unlined arrow functions, and thanks to e.g. prettier, they get formatted like this:

    `window.addEventListener(‘click’, event => this.handleEvent(event))`

    If you now quickly want to log the event, you can go like this:
    `window.addEventListener(‘click’, event => console.log(event) & this.handleEvent(event))`

    Using && here is not an option, as console.log doesn’t return anything truthy.
    Rewriting to add curly brackets just to insert a second line for the console.log statement..just takes too long.

    So what you can quickly do is prepend the log statement with a single `&` and both statements will be executed “in parallel”.

    Of course this is only useful when dealing with side effects only and the return value of the inline function is not actually used.

    Still i find it a useful trick to know.

    1. Hello Jovica,

      Nice use case you pointed out there. However, for cases like the one you mentioned above, I recommend using the Comma operator (`,`), which is what I normally use, like so:

      `window.addEventListener(‘click’, event => (console.log(event), this.handleEvent(event)))`

      The reason is because of the `&` operator will always return an integer while the `,` operator preserves the value of the last operand.

      Here is a simple scenario, compare the returned values of these two functions:

      FUNCTION 1:
      `const stringifyAnd = data => console.log(data) & JSON.stringify(data);`

      FUNCTION 2:
      `const stringifyComma = data => (console.log(data), JSON.stringify(data));`

  2. One piece not covered is bitwise shift, which is useful for setting flags in a clear way, for example.

    const LIST_FRACTION = 1 << 0; // (001)
    const LIST_UNIQUE = 1 << 1; // (010)
    const LIST_SORTED = 1 << 2; // (100)

    Beyond that, you don't need to check against the flag, since a match will be non-zero (truthy)

    if (flag & LIST_UNIQUE) {}

  3. Hi, Glad.

    Nice article. Lots of good information.

    Most of my programming is for discrete mathematics applications; I always have an eye open for ways to write more concise code and, ideally, programs that execute faster. If a built-in function, with its overhead, can be replaced by a simple bitwise operation, I tend to prefer the bitwise option.

    Good to see you discussed the method for checking if an integer is odd:

    if (value & 1)

    Bitwise operators can also be used to floor or truncate a real number. For example, say you want to take just the integer part of a positive floating point number. You could do it several ways:

    intVal = ~~floatVal;
    intVal = floatVal | 0;

    There are a few other ways to do it too. And keep in mind that if the numbers are negative, a check might have to be made first. BUT if you are working with positive numbers, this technique is good to keep in your back pocket for possible future use.

    And bitwise operations can be used to swap two integer variables without the use of a third, temporary, variable. Again, sometimes handy.

    One number manipulation technique I’d like to see: how to take the absolute value of a number by using bitwise operations. Any suggestion?

  4. > `(2^32 – 1), which is 2147483647`

    This is completely wrong. `(2^32 – 1)` is 4294967295. On the other hand 2147483647 equals to `(2^31 – 1)`.

  5. Thank You!

    Your explanation on the usage of the ‘NOT’ and the ‘AND’ operators taught me what I needed to know.

    JavaScript is not my first programming language (it’s around my 3rd/4th). I’ve recently been advancing my skills/knowledge, though. While doing so I recognized that I’d need a very concise way of changing a binary value.

    W3Schools.com has a nice reference page, but it doesn’t explain why anyone would use bitwise operation.

    This helps.

    Thank You!

Leave a Reply