Problem with return Javascript

1

I have always had little clarity on how to 'pick up' or 'capture' the value of the return, I know it is with functional expressions, but how?

My attempt:

var calc = document.getElementById('gosqrt');
calc.addEventListener("click", maths);

function maths() {
  
  var b = document.getElementById("sqrt").value;
  //alert(Math.sqrt(b));
    return Math.sqrt(b);
  
}

var um = maths();

document.write(um);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<input type="text" id="sqrt" placeholder="Square root"/>
  <input type="button" id="gosqrt" value="Calcular"/>
</body>
</html>
    
asked by Eduardo Sebastian 13.06.2017 в 04:16
source

1 answer

1

Analysis

If we look at the code, we can find the following line:

calc.addEventListener("click", maths);

This assigns a listener to the calc element, but What does this mean?

When you click on the calc element, it will execute a function.

Where is the problem?

The problem comes to occur in the fact that we are not saving the result returned from that function anywhere.

We have this line:

var um = maths();
document.write(um);

Simply run the maths() function, and voila, the valor returned from the function maths() is assigned to the variable um and the value is printed ... It does not pass nothing more.

Why does not the button work for us?

We have only assigned the listener , but we have not assigned the result of the function to any element.

How could we solve it?

One solution could be this:

/* Asignamos el listener */
var calc = document.getElementById('gosqrt');
calc.addEventListener("click", botonPresionado);

/* Creamos una variable que contendra el resultado */
var resultado;

/**
 * Funcion maths()
 * Calcula la raiz cuadrada
 */
function calcularRaiz() {  
  var b = document.getElementById("sqrt").value;  
  return Math.sqrt(b);  
}

/**
 * Funcion botonPresionado()
 * Funcion a ejecutar cuando se presione el boton
 */
function botonPresionado() {  
  resultado = calcularRaiz();
  alert(resultado);
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<input type="text" id="sqrt" placeholder="Square root"/>
  <input type="button" id="gosqrt" value="Calcular"/>
</body>
</html>

What have we done here?

We create a global variable , called resultado and in it we save the result of the function calcularRaiz() (previous maths ()) , and execute a alert() , to show the result of the operation.

    
answered by 13.06.2017 / 04:43
source