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:

Rxjs Adoption Guide: Overview, Examples, And Alternatives

RxJS adoption guide: Overview, examples, and alternatives

Get to know RxJS features, benefits, and more to help you understand what it is, how it works, and why you should use it.

Emmanuel Odioko
Jul 26, 2024 ⋅ 13 min read
Decoupling Monoliths Into Microservices With Feature Flags

Decoupling monoliths into microservices with feature flags

Explore how to effectively break down a monolithic application into microservices using feature flags and Flagsmith.

Kayode Adeniyi
Jul 25, 2024 ⋅ 10 min read
Lots of multi-colored blue and purplish rectangles.

Animating dialog and popover elements with CSS @starting-style

Native dialog and popover elements have their own well-defined roles in modern-day frontend web development. Dialog elements are known to […]

Rahul Chhodde
Jul 24, 2024 ⋅ 10 min read
Using Llama Index To Add Personal Data To Large Language Models

Using LlamaIndex to add personal data to LLMs

LlamaIndex provides tools for ingesting, processing, and implementing complex query workflows that combine data access with LLM prompting.

Ukeje Goodness
Jul 23, 2024 ⋅ 5 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