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
.