How to Represent Binary Numbers in JavaScript?

In JavaScript, you can represent binary numbers in the following ways:

  1. Using the Binary Number Syntax;
  2. Specifying Binary Number as a String.

If you're working with really large numbers, then perhaps using BigInt would be a good approach.

Using the Binary Number Syntax

Starting with ES6, you can use the binary number syntax to represent a binary number. To specify a binary number, you must prefix it with a leading zero followed by a lowercase or uppercase letter "B" (i.e. 0b or 0B).

For example, the following binary number syntax are equivalent:

// ES6+
const binNum = 0b101;

console.log(binNum); // 5
// ES6+
const binNum = 0B101;

console.log(binNum); // 5

Please note that if the digits after 0b (or 0B) are not 0 or 1, then a SyntaxError is thrown.

Specifying Binary Number as a String

To represent binary numbers in versions prior to ES6, you can simply use a string like so:

const binNum = '0101';

console.log(Number.parseInt(binNum, 2)); // 5

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.