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:

Vue logo over a brown background.

A guide to two-way binding in Vue

Learn how to implement one-way and two-way data binding in Vue.js, using v-model and advanced techniques like defineModel for better apps.

David Omotayo
Nov 22, 2024 ⋅ 10 min read
TypeScript logo over a pink and white background.

Drizzle vs. Prisma: Which ORM is best for your project?

Compare Prisma and Drizzle ORMs to learn their differences, strengths, and weaknesses for data access and migrations.

Temitope Oyedele
Nov 21, 2024 ⋅ 10 min read
Practical Implementation Of The Rule Of Least Power For Developers

Practical implementation of the Rule of Least Power for developers

It’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.

Timonwa Akintokun
Nov 21, 2024 ⋅ 8 min read
Rust logo over black marble background.

Handling memory leaks in Rust

Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.

Ukeje Goodness
Nov 20, 2024 ⋅ 4 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