
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
JavaScript program to take in a binary number as a string and returns its numerical equivalent in base 10
We are required to write a JavaScript function that takes in a binary number as a string and returns its numerical equivalent in base 10. Therefore, let’s write the code for the function.
This one is quite simple, we iterate over the string using a for loop and for each passing bit, we double the number with adding the current bit value to it like this −
Example
const binaryToDecimal = binaryStr => { let num = 0; for(let i = 0; i < binaryStr.length; i++){ num *= 2; num += Number(binaryStr[i]); }; return num; }; console.log(binaryToDecimal('1101')); console.log(binaryToDecimal('1101000')); console.log(binaryToDecimal('10101'));
Output
The output in the console will be −
13 104 21
- Related Articles
- How can we enter numerical values as a BINARY number in MySQL statement?
- Swapping string case using a binary number in JavaScript
- Interchanging a string to a binary string in JavaScript
- Check if given number contains only “01” and “10” as substring in its binary representation
- Program to add two binary strings, and return also as binary string in C++
- How to concatenate numerical vectors and a string to return a string in R?
- Which MySQL function returns a specified number of characters of a string as output?
- Converting string to a binary string - JavaScript
- Write a Golang program to convert a binary number to its decimal form
- Write a Golang program to convert a decimal number to its binary form
- String to binary in JavaScript
- Represent Int32 as a Binary String in C#
- Represent Int64 as a Binary string in C#
- How to add a number and a string in JavaScript?
- JavaScript Program to Find Maximum number of 0s placed consecutively at the start and end in any rotation of a Binary String

Advertisements