It's a matter of scope . Any variable created in a scope is available to all scopes that are nested in this scope. That's why the first code works. Some variables are created with global scope even in more internal scopes and this is terrible and should be avoided, so always use var
or let
.
If you call the calcula()
function in another scope it will not work. It works only in this case because even with var
in this case the variable assumes a global scope (it could be regional, but in this case it is global even.This type of scope is usually problematic, and should be avoided, it should only be used when it is too important and very carefully.
Note that these V
and R
variables can even be changed within the function, and this is somewhat dangerous. In a more complex codebase have access to a variable with that name that is not even what you want.
Consider that both codes are wrong. They work, but it is not ideal to do so. You can even do it, but you have to know very well what you are doing, when you do not know it is better to follow the safest route. This code should look like this:
function main() {
var V = prompt("Enrte com o valor da tensão");
var R = prompt("Entre com o valor da resistência");
var corrente = calcula(V,R);
document.write("O valor da corrente é ", corrente, "A");
}
function calcula(V, R) {
return V / R;
}
main()
Now try doing without parameter:
function main() {
var V = prompt("Enrte com o valor da tensão");
var R = prompt("Entre com o valor da resistência");
var corrente = calcula(V,R);
document.write("O valor da corrente é ", corrente, "A");
}
function calcula() {
return V / R;
}
main()
The local scope of the two variables prevents them from being seen in the other function.
Just because it works does not mean it's right.