It is a matter of scope. Every variable created in a scope is available for 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 function calcula()
in another scope it will not work. Only works in this case because even with var
in this case the variable takes a global scope (it could be regional, but in this case it is global. This type of scope is often problematic, and should be avoided, it should only be used when it is very important and very carefully.
Note that these variables V
and R
can even be changed within the function, and this is something dangerous. In a more complex code base have access to a variable with that name which 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 path. This code should be like this:
function main() {
var V = prompt("Entre 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()
I put in the Github for future reference.
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()
I put in the Github for future reference.
The local scope of the two variables prevents them from being seen in the other function.
Just because it works doesn’t mean it’s right.
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site
– Maniero