Javascript - Simple Calculator Example

In this Javascript example tutorial we will create simple Calculator using If-Else conditions. In this example we can learn how to use math operations in javascript like addition, substraction, multiplication...

 

Let write simple calculator example code

// Ask user to select the math operation symbol to perform actions
const operator = prompt('Select an operator ( +, -, * or / ): ');

// Ask user to enter numbers to perform above operations
const num1 = parseFloat(prompt('Enter first number: '));
const num2 = parseFloat(prompt('Enter second number: '));

let result;
// Write if...else condition 
if (operator == '+') {
result = num1 + num2;
}
else if (operator == '-') {
result = num1 - num2;
}
else if (operator == '*') {
result = num1 * num2;
}
else {
result = num1 / num2;
}
// Out put for the user operation on given numbers
console.log(`${num1} ${operator} ${num2} = ${result}`);

 

Output:

Select an operator ( +, -, * or / ): -

Enter first number: 77

Enter second number: 8

77 - 7 = 69

 

Subscribe For Daily Updates

100+ Python Pattern Examplespython pattern examples - star patterns, number patterns