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. I am studying specifically before continuing the course. Thanks!
– Caio Maciel