RhysE96 RhysE96 - 12 days ago 6
Javascript Question

Simple javascript calculator if statement

Im a newbie at JS but i have tried to create an if statement on my calculator, that when the result of a multiplication or addition etc is bigger than 20 an alert comes up. The calculator works fine but not the the if statement.

JS:

var a,b;
function setValues()
{
a = Number(document.getElementById("a").value);
b = Number(document.getElementById("b").value);
}

function sum()
{
setValues();
result = a+b;
alert("the sum is equal to "+result);
}
function rest()
{
setValues();
result = a-b;
alert("the rest is equal to "+result);
}
function mult()
{
setValues();
result = a*b;
alert("the operation is equal to "+result);
}
function div()
{
setValues();
result = a/b;
alert("the operation is equal to "+result);
}

if (result > 20) {
alert("heyy thats pretty big");
}

Answer

Your if statement should be inside each operator function like so:

function div()
{
  setValues();
  result = a/b;
  alert("the operation is equal to "+result);
  checkResult(result);
}

function checkResult(result){
  if(result > 20)
    alert("heyy thats pretty big");
}