Need to declare variables in a Javascript function

Asked

Viewed 410 times

0

Hello. I’m starting to learn programming logic. When I create a Javascript function, I declare and ask to return its value.

     function exemplo(teste){
              var saida = teste + 4;
              return saida;
     }

Well, when I’m gonna use the function, I’m re-declaring the output.

var teste = parseInt(prompt('Diga um número.'));          
var saida = exemplo(teste);
alert(saida);

If I ask to return the value of exit, why do I have to declare the variable again?

2 answers

1

You do not need to declare again. You can do this:

alert(exemplo(teste))

However, if you need to use this result in more than one place, in this case it is indicated to save the return in the variable. This way, you don’t need to call the method again every time this value is needed.

The fact that power doesn’t mean it’s more appropriate. Even just using this return once, you can choose to save the return on the variable so that the code is cleaner.

That way:

var saida = exemplo(teste);
alert(saida);

It’s more readable than that:

alert(exemplo(teste))

In the same way, you could do it:

alert(exemplo(parseInt(prompt('Diga um número.'))))
  • Thank you very much. I am studying specifically before continuing the course. Thanks!

1


You do not need to declare it again. Simply return the direct sum to return:

function exemplo(teste){
  return teste + 4;
}

This has to do with scope of variables. When you declare var saida within the function, that saida will have local scope, will be restricted within the function because of the var.

On the other hand, the var saida out of the function, has global scope, can be used anywhere in the code. Or, if you omit the var in saida within the function, it has a global scope.

For example:

function exemplo(teste){
  soma = teste + 4;
  return soma;
}

var teste = parseInt(prompt('Diga um número.'));          
var saida = exemplo(teste);
alert(saida + "/" + soma);

In the above code 2 global variables will be created: saida and soma, with the same values.

Another example:

function exemplo(teste){
  var soma = teste + 4;
  return soma;
}

var teste = parseInt(prompt('Diga um número.'));          
var saida = exemplo(teste);
alert(saida + "/" + soma);

In this code above will give error, because the variable soma does not exist outside the function, because it was declared within it with var.

  • Thank you very much for your attention. I will research more about.

Browser other questions tagged

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