2023-04-13
4367
#vanilla javascript
Glad Chinda
4261
110
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:

How To Create Heatmaps In Javascript: Exploring The Heat Js Library

How to create heatmaps in JavaScript: The Heat.js library

This tutorial will explore the application of heatmaps in JavaScript projects, focusing on how to use the Heat.js library to generate them.

Oghenetega Denedo
May 8, 2024 ⋅ 7 min read
Eleventy Adoption Guide: Overview, Examples, And Alternatives

Eleventy adoption guide: Overview, examples, and alternatives

Eleventy (11ty) is a compelling solution for developers seeking a straightforward, performance-oriented approach to static site generation.

Nelson Michael
May 7, 2024 ⋅ 8 min read
6 CSS Tools For More Efficient And Flexible CSS Handling

6 CSS tools for more efficient and flexible CSS handling

Explore some CSS tools that offer the perfect blend of efficiency and flexibility when handling CSS, such as styled-components and Emotion.

Fimber Elemuwa
May 7, 2024 ⋅ 7 min read
Leveraging React Server Components In Redwoodjs

Leveraging React Server Components in RedwoodJS

RedwoodJS announced support for server-side rendering and RSCs in its Bighorn release. Explore this feature for when it’s production-ready.

Stephan Miller
May 6, 2024 ⋅ 9 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