Why are you returning undefined?

1

Why does my function return undefined ? Where does that come from?

function Maths(){
  
  this.raiz = function(numero){
    if(numero<0) return console.log("No disponible para números imaginarios");
    return numero%1===0 ? Math.sqrt(parseInt(numero)) : Math.sqrt(parseFloat(numero));
  };  
}

var b = new Maths();
console.log(b.raiz(-4));

If you try to get negative root, you will return a message in console that is not available for imaginary numbers and therefore in return , the function will end but also returns undefined . Why?

    
asked by Eduardo Sebastian 31.08.2017 в 04:14
source

1 answer

4

Code

function Maths() {

  this.raiz = function(numero) {
    if (numero < 0) return "No disponible para números imaginarios";
    return numero % 1 === 0 ? Math.sqrt(parseInt(numero)) : Math.sqrt(parseFloat(numero));
  };
}

var b = new Maths();
console.log(b.raiz(-4));

Explanation

What happens is that the function console.log does not return any value , so when you write:

return console.log("Hola Mundo");

The function will return undefined , since this function returns nothing.

Solution

You can make a direct return of the message:

return "No disponible para números imaginarios";

To thus later print it from where you call the function.

    
answered by 31.08.2017 в 04:24