Is there a way for me to calculate the square of a number generated by a function?

Just starting out with Javascript and coding, I'm having trouble squaring a number that comes from a function. I've outlined below what I am trying to achieve. Thank you in advance for your help.

// CONVERT BINARY TO DECIMAL 

// (100110)2 > (1 × 2⁵) + (0 × 2⁴) + (0 × 2³) + (1 × 2²) + (1 × 2¹) + (0 × 2⁰) = 38

let binary= prompt("Write a Binary Number");

function binaryToDecimalConverter(binary){
    let decimal=0;
    let power=0;
    for(let i=binary.length-1; i>=0; i--){
        decimal+=Number(binary.charAt(i)) * Math.pow(2,power);
        power++;
    }
    console.log("Decimal : " + decimal);
    console.log(squareIt(decimal));
    
}


binaryToDecimalConverter(binary);

function squareIt(decimal){  
    let sNumber=decimal.toString();
    let total=0;
    for(let i=sNumber.length-1; i>=0; i--){
        total+=Number(sNumber.charAt(i))*Math.pow(Number(sNumber.charAt(i)),2);
        
    }
    return total;    
}

I am attempting to convert a binary number entered by the user to decimal. Additionally, I am looking to square each digit of that number and then sum them up.

Answer №1

To convert a binary number to decimal and then square the digits, you can split the number into individual characters and utilize Array::reduce():

let binary= prompt("Enter a Binary Number");

function binaryToDecimalConverter(binary){
    let decimal=0;
    let power=0;
    for(let i=binary.length-1; i>=0; i--){
        decimal+=Number(binary.charAt(i)) * Math.pow(2,power);
        power++;
    }
    console.log("Decimal : " + decimal);
    console.log(squareIt(decimal));
    
}


binaryToDecimalConverter(binary);

function squareIt(decimal){  //How can I calculate (3^2 + 8^2) if decimal is 38?
    return decimal.toString().split('').reduce((sum, digit) => sum + digit * digit, 0);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to use jQuery AJAX to make changes to an HTML element that will be permanent even after the page is refreshed?

Starting out with codeigniter, I am working on building an ecommerce website. Every time a user clicks the "Add to cart" button in my view, I utilize jquery ajax to send a request to a controller function. This function then returns two variables: count ( ...

Calculating date discrepancies with JavaScript

Two fields are present, one for the start date and one for the end date. I would like to display the date difference in another text box when the user selects dates from a date picker. Although I have made some progress on this, I believe that there are st ...

Is it possible to create a replicating text box in AngularJS that multiplies when entering input

I am experimenting with creating a sequence of text boxes that dynamically generate new empty text boxes as the user enters information into each one. Each text box is required to have an ng-model value associated with it, and they should all be generated ...

Vue's innate lifecycle hook

I am looking for a way to automatically run a specific function as a beforeMount hook in every component of my Vue project without having to declare it individually. Essentially, I want a default behavior where if the hook is not explicitly stated in a com ...

Issue encountered when setting up Webpack development server resulted in the failure to generate

Is anyone else experiencing difficulties when trying to create a static folder named "dist"? Package.json "scripts": { "start": "webpack-dev-server --open", "dev": "webpack --mode development --watch ./frontend/src/index.js --output ./frontend/static/fr ...

Checking for offline status in a Cordova app using Angular

I have implemented the following code to determine whether my Cordova application is online or offline. var networkState = navigator.connection.type; var states = {}; states[Connection.UNKNOWN] = 'Unknown'; states[Connection.ETHERNET] = ' ...

Encountering connectivity issues with MongoDB client and struggling to insert data while utilizing promises

Currently, I am experimenting with nodeJS and encountering an error when trying to establish a connection to the MongoDB Client. I have implemented promises for improved readability but am facing issues connecting. The code involves connecting to the datab ...

retrieve scanned image information with node.js

Hey, I'm currently dealing with an issue that involves a form containing various types of questions such as boolean and text field answers. The user fills out the form, scans it, then uploads it to a node.js server. The node server will extract answe ...

Issue with Backbone Event Dropping Functionality

I am facing an issue with my dashboard that has two backbone Views. One of the views consists of various drop zones while the other contains items with draggable="true". Surprisingly, the drop event is not being triggered in these drop zones; however, they ...

Typescript's Nested Type Assignments

Simply put, I'm making an API call and receiving the following data: { getUserInfo: { country: 'DE', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c48594f487c59445d514c5059125f5351">[e ...

Can an event be initiated on dynamically loaded iframe content within a document using the jQuery "on" method?

Is there a way to include mousemove and keypress events for iframes? The code provided seems to work well with existing iframes on the page, but it doesn't seem to work for dynamically created frames in the document using JavaScript. $('iframe&a ...

Having trouble with React Page crashing when trying to access the component state

I'm attempting to create a side-bar menu that swaps out content in a <main> tag when menu buttons are clicked. However, I'm facing an issue where the page becomes unresponsive and eventually crashes due to React issues while trying to read ...

What are the steps to launching a yarn app on a dev server?

I've always stuck with npm and never ventured into using yarn or webpack explicitly. The code from this repository needs to be executed: https://github.com/looker-open-source/custom_visualizations_v2 I'm looking for a way to run it like a develo ...

mongojs implementation that allows for asynchronous query execution without blocking

Forgive me for asking what may seem like a silly question, but I am struggling to make this work. Currently, as part of my learning journey with node.js and mongojs, I have encountered the following issue: Below is my server.js file server.get("/", funct ...

Demonstrate how to pass a newline character from Ruby on Rails to JavaScript

I am working with a .js.erb file that is activated by a JavaScript function. Within this js.erb file, I have the following snippet of code: event = <%=raw @event.to_json %> $('#preview-event-body').html(event.body); The value of event.bo ...

Text field value dynamically changes on key press update

I am currently working on the following code snippet: {% for item in app.session.get('aBasket') %} <input id="product_quantity_{{ item['product_id'] }}" class="form-control quantity" type="text" value="{{ item['product_quan ...

Is there a way to execute two files concurrently in JavaScript using node.js?

I'm a beginner in the world of Javascript and Node.js, and I've encountered some issues while trying to test code I recently wrote. Specifically, I am attempting to test the code within a file named "compareCrowe.js" using another file named "tes ...

Using AngularJS to Bind a $scope Variable

As I work on constructing a directive in angularJS, I come across an issue where I am attempting to bind an object property from another variable to an HTML element. Here is an example: angular.module('ng.box', codeHive.angular.modules) .directi ...

JQuery Tic Tac Toe Duel: Face Off Against Your Friend in a Thr

Looking for some advice here. I'm new to game development and currently working on a 2 Player Tic Tac Toe game. I need help with implementing the game functionality. Any suggestions? I want to disable the "div" once a player clicks on it, but I' ...

What is the best way to extract the value from a Material UI Slider for utilization?

I am looking to capture the value of the slider's onDragStop event and store it as a const so that I can use it in various parts of my code. However, I am unsure about how to properly declare my const sliderValue and update it. Any guidance on where a ...