Build a Simple Calculator
Building a simple calculator is a fun way to practice everything you've learned so far in JavaScript. You'll use buttons, events, basic math, and the DOM together to create a real, working mini-project. This kind of hands-on project helps you connect the dots between theory and real-world coding.
Using buttons and click events
First, you’ll need buttons for numbers and math operations like +, -, *, and /. Each button will listen for a "click" event. When a button is clicked, it should either add a number to the display or perform an action like clearing the result or calculating the answer.
Example of setting up a button click:
const button = document.querySelector("#one");
button.addEventListener("click", function() {
console.log("Button 1 clicked");
});
You’ll do something similar for all your calculator buttons, but instead of just logging a message, you’ll update the screen with numbers or operations.
DOM + math in action
The calculator’s "screen" can be a simple <div>
or <input>
where you show the user's input and the results. When a user presses numbers and operations, you update the screen. When they press "equals," you use JavaScript to actually do the math.
Example:
let result = eval("2+3*4"); // result will be 14
In real projects, using eval()
can be risky, but for a simple calculator project, it’s an easy way to handle calculations.
You’ll connect the math with the DOM by updating the text of the display element based on user actions.
Clear Button Functionality
Adding a "Clear" button is super useful. It lets users reset the calculator screen without refreshing the page. It’s a good practice to make your app easy and friendly to use.
Example:
const clearButton = document.querySelector("#clear");
clearButton.addEventListener("click", function() {
display.value = "";
});