Javascript function for splitting returning Nan

Asked

Viewed 211 times

1

Faaaala staff, I have a question...

Why when I pass two values per parameter in this division function is returning Nan? If I add values the variables before that is fine. But when I pass the function call the problem appears.

var divicao = function (valor1, valor2){
    var resultado = valor1 / valor2;
    return resultado;
}

Example where to return Nan:

 console.log(divicao(1/2));
  • You could add an example of use that returns a question NaN?

  • Yes I will add, pardon me

2 answers

2


You are calling the wrong function, you have to separate the parameters by comma:

var divicao = function (valor1, valor2){
    var resultado = valor1 / valor2;
    return resultado;
}

//so coloquei para um alert para ficar mais fácil de ver o retorno
alert(divicao(1,2))

// no console
console.log(divicao(1,2))

Improving your code a little bit:

//Você pode retornar direto o valor da divisão
var divicao = function (valor1, valor2){
    return valor1 / valor2;
 }

//so coloquei para um alert para ficar mais fácil de ver o retorno
alert(divicao(1,2))

// no console
console.log(divicao(1,2))

  • 2

    Just to complete, divisao(1/2) is equivalent to divisao(0.5, undefined)

  • Guys thanks, I ended up not paying attention to it in the call of the function, thanks for the help!!.

1

Actually the logic of your code is correct, the problem is in the way you call the function divicao(1/2).

Usually the parameters in javascritp are separated by comma ,, and in this serious case: divicao(1,2).

Note that if you print the parameters you would have the following result: valor1=0.5 and the valor2=undefined.

  • Guys thanks, I ended up not paying attention to it in the call of the function, thanks for the help!!.

Browser other questions tagged

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