Need to declare variables in a Javascript function

0

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

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

Well, when I'm going to use the function, I'm declaring the output again.

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

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

    
asked by anonymous 03.12.2017 / 03:22

2 answers

1

You do not need to declare it again. It would just return the direct sum in return :

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

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

On the other hand, var saida out of function, has global scope, can be used in any part of the code. Or, if you omit var in saida within the function, it becomes globally scoped.

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);

This code above will give error, because the soma variable does not exist outside of the function because it was declared inside it with var .

    
03.12.2017 / 04:15
1

You do not have 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 recommended to save the return on the variable. That way, you will not have to call the method again every time this value is needed.

Being able does not mean that it is more appropriate. Even just using this return once, you can choose to save the return on the variable to make the code cleaner.

This form:

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

It's more readable this way:

alert(exemplo(teste))

Similarly, you could do this:

alert(exemplo(parseInt(prompt('Diga um número.'))))
    
03.12.2017 / 04:13