Help with my code to add, subtract, multiply and divide please


#1



Hello all. I'm not writing about a specific exercise. But, using what I've learned so far (I'm about 50% through the JavaScript course), I've been attempting to write code that will do math.

I first setup a simple code to do addition:

alert("Here's an addition calculator");
var firstNum = prompt("Enter the first number");
var secondNum = prompt("Enter the second number");
var total = Number(firstNum) + Number(secondNum);
alert("The total is" + " " + total);

That worked fine and I used the same template to make one that subtracts, multiplies and divides as well. They all work fine individually. Then, I got more ambitious and wanted to combine them all and give the user choices of which type of math to do. I attempted to use if else statements, but can't seem to get it to work. Here's what I have so far...Any suggestions?


alert("Here's a calculator");
var mathType = prompt("Would you like to add, subtract, multiply or divide?");

if(mathType = "add") {
var firstNum = prompt("Enter the first number");
var secondNum = prompt("Enter the second number");
var total = Number(firstNum) + Number(secondNum);
alert("The total is" + " " + total);
}

else if(mathType = "subtract") {
var firstNum = prompt("Enter the first number");
var secondNum = prompt("Enter the second number");
var total = Number(firstNum) - Number(secondNum);
alert("The total is" + " " + total);
}

else if(mathType = "multiply") {
var firstNum = prompt("Enter the first number");
var secondNum = prompt("Enter the second number");
var total = Number(firstNum) * Number(secondNum);
alert("The total is" + " " + total);
}

else if(mathType = "divide") {
var firstNum = prompt("Enter the first number");
var secondNum = prompt("Enter the second number");
var total = Number(firstNum) / Number(secondNum);
alert("The total is" + " " + total);
}


#2

I can immediately see that you are using an assignment (=) where you probably were trying to do a Boolean test (===).


#3

Thank you so much!! That's all it was!!