Javascript declare variables outside the function

Asked

Viewed 136 times

0

I just want the sum of these two numbers, it works when I declare the variables within the function, why isn’t it working like this? I’m getting Nan.

<form>
    <input type="number" id="num1">
    <input type="number" id="num2">
    <input type="button" value="oi" onclick="calpp()">
</form>
<script>
    var x = parseInt(document.getElementById('num1').value, 10);
    var y = parseInt(document.getElementById('num2').value, 10);

    function calpp(){
        alert(x+y);
    }
</script>
  • Please rewrite your question in Portuguese, since here is the Portuguese stackoverflow.

  • And why you want to assign values outside the function?

2 answers

2


The problem is the Javascript execution sequence.

In this your code, when the browser loads and processes your HTML, it puts on the screen the 2 inputs, and then processes the script tag and executes the code that is inside.

At this point, it already takes the content of the inputs and stores in the variables, but the page has just loaded and the user has not yet made any interaction, so the fields are empty, so it converts "empty" to integer and stores in the variables x and y.

When the user clicks on the button, it only recovers those values that are already fixed as invalid (because it was processed when loading the page) and the calculation goes wrong.

You can see this if you already assign an initial value to inputs:

  var x = parseInt(document.getElementById('num1').value, 10);
  var y = parseInt(document.getElementById('num2').value, 10);

  function calpp(){
      alert(x+y);
  }
<form>
    <input type="number" id="num1" value="5">
    <input type="number" id="num2" value="3">
    <input type="button" value="oi" onclick="calpp()">
</form>

With the initial values your code works, but if the user changes it will stay forever with the initial values because the lines that recovers the values of the inputs and saved in the variables was already executed when the page was loaded.

That’s why when you move into the function it works! When it is inside the function and you click on the button, the values are recovered at the time of the input, so the value that is typed there at that time.

It is important to understand this flow of HTML, Javascript and CSS execution to avoid this kind of situation.

Finally, your code with the correction:

// Podemos até declarar as variáveis fora da função
var x;
var y;

function calpp(){
  // Mas devemos sempre recuperar os dados do estado atual da aplicação
  x = parseInt(document.getElementById('num1').value, 10);
  y = parseInt(document.getElementById('num2').value, 10);
  
  // E por fim exibi-los
  alert(x+y);
}
<form>
    <input type="number" id="num1">
    <input type="number" id="num2">
    <input type="button" value="oi" onclick="calpp()">
</form>

1

This is a question of running order in Javascript. You can declare the variables outside and take the value inside the function and parse as shown:

var x = document.getElementById('num1');
var y = document.getElementById('num2');

function calpp() {
  var a = parseInt(x.value, 10);
  var b = parseInt(y.value, 10);
  
  console.log(`Valor de A: ${a} - Tipo: ${typeof a}`);
  console.log(`Valor de B: ${b} - Tipo: ${typeof b}`);
  console.log(`Soma: ${a + b}`);
}
<form>
  <input type="number" id="num1">
  <input type="number" id="num2">
  <input type="button" value="oi" onclick="calpp()">
</form>

  • 1

    In fact I believe that it is not a matter of scope the real problem, but rather the Javascript execution flow

  • 1

    I agree with @Diegomarques, I think that although the scope is what changes the functioning of the code, the real problem is in the order of the calls. I think this response can be harmful to beginners and should be edited.

  • 1

    @Diegomarques and Lucas Espindola. Yes, yes, I was missing the correct word there yesterday, but you defined exactly what I meant, Javascript execution order. Post Edited, many thanks to both!

Browser other questions tagged

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