2
var n1 = 10;
if (n1 == 10) {
var n2 = 45;
}
console.log(n2);
The above example works perfectly by printing the value of n2
in the console
browser in this n2
is within the command if
and is accessible, but when trying to pick up a variable within a function
it is no longer accessible and I can no longer get the value of the variable n2
and an error is returned (Uncaught ReferenceError: n2 is not defined
).
var n1 = 10;
function a() {
var n2 = 45;
}
console.log(n2);
My question is why I can’t access the variable of a function
, but of command if
can I? sorry for the simplicity of the code, but I’m a complete beginner, I left the Portugol and I’m trying to learn Javascript.
then it is only in the functions that a scope is created automatically in the case of other commands not?
– user173282
@draw in the case of
var
, yes– guijob
@guijob, thank you very much!
– user173282