Result Undefined when calling function in calculator

Asked

Viewed 130 times

1

This script for calculation but it returns undefined, where I’m going wrong?

var num1 = parseInt(prompt("Digite um número: "))
var operacao = prompt("Digite a operação: ")
var num2 = parseInt(prompt("Digite outro número: "))

function calculo(num1, num2, operacao){
  if (operacao == 'soma'){
    resultado = num1 + num2
    return resultado
  } else if (operacao == 'subtracao'){
    resultado = num1 - num2
    return resultado
  }
}

document.write(calculo())
  • You are invoking the function without passing any arguments.

2 answers

7


Because you are not passing the arguments to the function.

I took advantage and improved the readability of the code, putting together what is together, putting ; because it works but there is case that gives problem and then you will be looking without understanding the error (get used to do right, it does not cost to type an extra character to give more robustness to the code) and I removed the creation of the variable that did not make sense there, mainly because in the posted form it is created in global scope and this should not happen.

The code still runs risks if something is typed wrong, but that’s just improvement.

function calculo(num1, num2, operacao){
    if (operacao == 'soma') return num1 + num2;
    else if (operacao == 'subtracao') return num1 - num2;
}

var num1 = parseInt(prompt("Digite um número: "));
var operacao = prompt("Digite a operação: ");
var num2 = parseInt(prompt("Digite outro número: "));
document.write(calculo(num1, num2, operacao));

I put in the Github for future reference.

The code would work if the function had no parameters, since the global serial scope variables used directly by the function, but it is not ideal to do this, I am saying to complete information. Since it has parameters and nothing is sent to them then the values are undefined.

2

You defined 3 arguments in the function, but when calling it did not provide them, so it does not work, just need to provide the data to work:

var num1 = parseInt(prompt("Digite um número: "))
var operacao = prompt("Digite a operação: ")
var num2 = parseInt(prompt("Digite outro número: "))

function calculo(num1, num2, operacao){
  if (operacao == 'soma'){
    resultado = num1 + num2
    return resultado
  } else if (operacao == 'subtracao'){
    resultado = num1 - num2
    return resultado
  }
}

document.write(calculo(num1, num2, operacao))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.