Home > front end >  JS calculator not working. Operators are not functioning. Every time I run the calc, it only adds
JS calculator not working. Operators are not functioning. Every time I run the calc, it only adds

Time:08-29

Kindly help. I am very new to JavaScript. I have been trying to figure this out for about 3 hours now. nothing seems to work. operators seem to be not stable. for example if i subtract 6-6, it'd still give me 12, i.e operators only add in all situations.Favor is appreciated.

enter code here

inp1 = prompt("Enter in a number");
inp1 = Number.parseInt(inp1);
let js1 = inp1;


op = prompt("Enter an operator");
op = [" ", "-", "*", "/"];

inp2 = prompt("Enter another number");
inp2 = Number.parseInt(inp2);
let js2 = inp2;

function addition(x, y) {
    return (x   y);
}
function subtraction(x, y) {
    return (x - y);
}
function multiplication(x, y) {
    return (x * y);
}
function division(x, y) {
    return (x / y);
}

if (op = " ") {
    console.log(addition(js1, js1));

}
else if (op = "-") {
    console.log(subtraction(js1, js2));
}
else if (op = "*") {
    console.log(multiplication(js1, js2));
}
else if (op = "/") {
    console.log(division(js1, js2));
}
else {
    console.log("Sorry! An Error has occurred");
}

CodePudding user response:

You are not comparing them in the if statement, instead you are assigning. What you're looking for is this:

if(op === " ") {
   //add
} else if(op === "-") {
   //subtract
} 

You should also look into JavaScripts different ways of comparing https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

CodePudding user response:

fist problem in

op = [" ", "-", "*", "/"];

so after your get the operator from a user, you assign it to a new value

and also

if (op = " ") {}
else if (op = "-"){}

this assignment operator not the comparator instead use

if (op === " ")
  • Related