FrontendDeveloper.in

ECMAScript question detail

Binary and Octal

ES5 provided numeric literals in octal (prefix 0), decimal (no prefix), and hexadecimal ( 0x) representation. ES6 added support for binary literals and improvements on octal literals.

1. Binary literals:

Prior to ES5, JavaScript didn’t provide any literal form of binary numbers. So you need to use a binary string with the help of parseInt()

const num = parseInt('110',2);
console.log(num); // 6

Whereas ES6 added support for binary literals using the 0b prefix followed by a sequence of binary numbers (i.e, 0 and 1).

const num = 0b110;
console.log(num); // 6

2. Octal literals:

In ES5, to represent an octal literal, you use the zero prefix (0) followed by a sequence of octal digits (from 0 to 7).

const num = 055;
console.log(num); // 45

let invalidNum = 058;
console.log(invalidNum); // treated as decimal 58

Whereas ES6 represents the octal literal by using the prefix 0o followed by a sequence of octal digits from 0 through 7.

const num = 055;
console.log(num); // 45

const invalidNum = 028;
console.log(invalidNum); // treated as decimal 28

Remember If you use an invalid number in the octal literal, JavaScript will throw a SyntaxError as below,

const invalidNum = 028;
console.log(invalidNum); // SyntaxError
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399