There seems to be an issue with the functionality of the operators in the Calculator Javascript

I'm currently working on a Javascript calculator project for FreeCodeCamp and encountering an issue with the code. Whenever I input an operator like "-", "+", "x", etc., the numbers in the history section start repeating themselves. For example, if I enter "5", then "5" appears in the history area. Subsequently, when I input "+", the history displays "5+5+".

My objective is to make the calculator function similar to the one found on Mac computers. In other words, when I input "5" followed by "+", I want the "5" to remain in the display area while "5+" appears in the history section until the next number is pressed. It should then display the next number while the history shows "5+6". How can I resolve these issues?

You can view my codepen link here: https://codepen.io/kikibres/pen/MEQvqv

Code snippet:

function addOperator(keyitem){
    addNumber(keyitem);
    subMath += mainMath;
    mainMath = keyitem;
  };

******************************UPDATE********************************** I managed to solve the repetition issue in the history area. However, I'm struggling with the display problem. Currently, every time I click on a number like "7" and then an operator like "+", the number in the display area resets to "0". Furthermore, after the operator, if I click on another number like "3", it displays as "03" in the display area... Here is my updated code snippet:

function addOperator(keyitem){
    if(mainMath == "0"){
      return;
    }
    subMath += keyitem;
    mainMath = "0";
  };

Answer №1

To tackle the second issue, it's essential to separate the display logic from the calculation logic. The goal is:

  • Enter a number => Display the number or the result using separate functions and variables
  • Enter a number or an operator => Perform the calculation using different functions and variables

The current code blends these two logics together, causing confusion.

To assist you in resolving this issue, consider using a debugger to step through your code or implement utility functions like this:

/* Your JavaScript code */
/* Your CSS code */
/* Your HTML code */

By following this approach, you can easily identify and correct the problem, as shown here:

subMath = at bottom of addOperator 8+8+
.

Another potential solution may involve adopting an alternative method, such as the one presented below (with variations in behavior but adaptable to your requirements):

/* Another JavaScript implementation */
/* Another CSS code */
/* Another HTML code */

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

The event.target.x attribute on the <i /> tag element

In my code, there is an <i name="documentId" onClick={this.openDocument}/> element with the onClick method defined as follows: openDocument(event) { const { name } = event.target; console.log('name', name); console.log('target&a ...

JavaScript module encounters an uncaught error: Attempting to assign a value to a constant variable

In another module, I defined a variable in the following manner: // module1.js let directory; export { directory }; Now, I am trying to access it in a separate module like so: // module2.js import { directory } from '../js/module1.js'; directo ...

The JQuery .ajax() function is not functioning properly, although the success method is still executing

Having issues with an ajax call on a webpage. The WebMethod is working fine. Potential problem - ajax method called from UserControl embedded in a content page within a master page, accessible only after .Net authentication. Including this info for transp ...

Verify the presence of an image

I have a code snippet that I use to refresh an image in the browser. However, I want to enhance this code so that it first checks if the image exists before displaying it. If the image does not exist, I want to display the previous version of the picture i ...

What's the reason my JavaScript isn't functioning properly?

Brand new to coding and I'm delving into the world of Javascript for the first time. In my code, there's a checkbox nestled within an HTML table (as shown below). <td><input type="checkbox" id="check1"/> <label th:text="${item.co ...

The issue I am facing is that the MDCSelect:change event does not seem to be functioning properly

Is there a way to get MDCSelect:change to work properly before appending all options? If I put MDCSelect:change after the list append, it works but the UI doesn't look right. Question: How can I make MDCSelect:change work without affecting the UI ap ...

What is the best way to refresh a page with AngularJS?

I have a link that, when clicked by the user, triggers a page reload. I accomplished this using the method below...... HTML <div data-ng-hide="backHide" class="offset6 pull-right"> <a href="" data-ng-click="backLinkClick()"><< Back ...

Scheduled Job unable to complete post request

(I am completely new to the world of JavaScript, node.js, and Heroku so I apologize in advance if my question is not very clear) I recently set up a Heroku node.js application with a scheduled task that should run every hour. The task does run as expecte ...

Preventing simultaneous AJAX requests with a single click

I am facing a challenge with handling multiple AJAX requests. Whenever a user clicks on a button, an AJAX request is triggered to enter a record into the database. However, if the user clicks on the button rapidly multiple times, it results in multiple sim ...

Struggling with navigating JSON data in JavaScript and facing difficulties sorting the array

I am currently facing the challenge of organizing data obtained from an API using JavaScript. JavaScript Code to Retrieve Data: function getResults() { var url = $.getJSON("http://api.api.com&leagues=SOCENGPRE&lang=en&format=jsonp&cal ...

Using a Second List Element in CSS Image Rollover Map with jQuery

I have been utilizing this interactive map from Wolf's website, but I am interested in incorporating a secondary list of countries alongside the existing one as the base for the script. However, due to presentation reasons, the second menu cannot resi ...

Utilizing CSS to Select Specific Sections

I'm curious about how to target a section element with a specific id like #dress in CSS3. Here is my code snippet: <section id="dress"> <p>Lorem Ipsum..................................of Lorem Ipsum.<> </section> Here's ...

CSS3 flip effect on hover and click causing issues

I have successfully implemented a card flip effect using CSS3. The card is flipped using jQuery and CSS CSS .flipped { -webkit-transform: rotateY( 180deg ); -moz-transform: rotateY( 180deg ); -o-transform: rotateY( 180deg ); transfor ...

Customizing error messages in Joi validationorHow to show custom

Hi there, currently I am utilizing "@hapi/joi": "^15.1.1". Unfortunately, at this moment I am unable to upgrade to the most recent Joi version. This represents my validation schema const schema = { name: Joi.string() .all ...

What is the best way to incorporate this HTML and script into a React component?

After receiving the embedded HTML and script from a platform, I discovered that a button triggers the script. It was originally designed to be embedded on a website, but I am attempting to integrate it into a React application. Here is the code provided fo ...

The border-radius property in CSS selectively rounds only one corner of the modal div window

There seems to be an issue with the border-radius property on modal divs in my project. When I apply the property, only one or two corners of the div round while the other corners remain unchanged. For a visual reference, please check out this image linke ...

How can we ensure that the previous selection is cleared in jQgrid only if the checkbox is not clicked

I've set up a grid with the option for multiselect: true so that I can delete multiple rows at once. When the onSelectRow event is triggered, data related to the ID is loaded and shown to the user. Everything seems to be working fine in this example ...

Adding additional text within the paragraph will result in the images shifting backwards when utilizing flexbox

It seems like there might be something obvious that I'm missing here, but essentially my goal is to create a footer with 2 columns and 2 rows. In each column, there will be an icon (32x32) and 2 lines of text next to it. The issue I'm facing is ...

What is the best way to transfer form input data from a child component to the parent component in React?

Recently delving into the world of React, I decided to experiment with forms. My project idea was straightforward - create a form component with input fields that, upon clicking submit, would pass the input values to the parent component ('App') ...

Issue with Selenium locating element within a GWT application

Looking to extract the text/value from an Element in a GWT app. You can find the app and the Element at the following locations: -navigate to -select "Products" -select "Software" -select "Rotary indexing table" -select "Next" -select "Next" again Y ...