⚡
Build a Calculator 🧮
Intermediate
150 XP
60 min
Lesson Content
Build a Calculator 🧮
Create a functional calculator that handles basic math operations. Great for learning JavaScript logic!
Calculator Logic
let currentValue = 0;
let operator = null;
let previousValue = 0;
function calculate(a, op, b) {
switch(op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
default: return b;
}
}
function handleOperation(op) {
if (operator) {
currentValue = calculate(previousValue, operator, currentValue);
}
operator = op;
previousValue = currentValue;
currentValue = 0;
}Example Code
Build calculator logic
function calculate(a, op, b) {
switch(op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return b !== 0 ? a / b : 'Error';
default: return b;
}
}
function performCalculation() {
return calculate(10, '+', 5);
}
console.log('Result:', performCalculation());Expected Output:
Result: 15
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code