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:

Actix Web Adoption Guide: Overview, Examples, And Alternatives

Actix Web adoption guide: Overview, examples, and alternatives

Actix Web is definitely a compelling option to consider, whether you are starting a new project or considering a framework switch.

Eze Sunday
Mar 18, 2024 ⋅ 8 min read
Getting Started With NativeWind: Tailwind For React Native

Getting started with NativeWind: Tailwind for React Native

Explore the integration of Tailwind CSS with React Native through NativeWind for responsive mobile design.

Chinwike Maduabuchi
Mar 15, 2024 ⋅ 11 min read
Developing A Cross Platform Tv App With React Native

Developing a cross-platform TV app with React Native

The react-tv-space-navigation library offers a comprehensive solution for developing a cross-platform TV app with React Native.

Emmanuel Odioko
Mar 14, 2024 ⋅ 10 min read
Essential Tools For Implementing React Panel Layouts

Essential tools for implementing React panel layouts

Explore some of the best tools in the React ecosystem for creating dynamic panel layouts, including react-resizable-layout and react-resizable-panels.

David Omotayo
Mar 13, 2024 ⋅ 8 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