In the Javascript
there are two types of scope, which are global and local.
Global scope is when you define a variable outside the code block of a function, so the variable is accessible to all the code.
For example:
var variavelGlobal = 10;
function funcOne() {
alert(variavelGlobal);
}
function funcTwo() {
alert(variavelGlobal + 10);
}
funcOne();
funcTwo();
Local scope is when you define a variable within a function, so it is only accessible within that function.
For example:
function funcOne() {
var variavelLocal = 10;
alert(variavelLocal);
}
function funcTwo() {
alert(variavelLocal + 10);//Um erro será lançado.
}
funcOne();
funcTwo();
Observing: Whenever variables are created in Javascript, consider using the reserved word var
, because without its use within the scope of a function, the variables within it have become global.
For example:
function funcOne() {
variavelLocal = 10;//Sem a palavra reservada 'var'.
alert(variavelLocal);
}
function funcTwo() {
alert(variavelLocal + 10);//Não será lançado um erro, pois 'variavelLocal' é global.
}
funcOne();
funcTwo();
To answer your question, the variables defined within the scope of a function only cease to exist outside the local scope, which is outside the function, in the global scope, so they are not accessible, but they always existed within the scope of the function where they were defined. When this function is executed and when this function finishes its execution they are deleted until the setTimeout
end up.
Yes, I understand that they are deleted when the function runs, but I noticed a flaw as noted in the question when I call
setTimeout
.– Klaider
setTimeout is inside the function where the variable 'a' was created, then the variable 'a' will still exist, because setTimeout belongs to its execution block.
– Yure Pereira
But the function block will already have run before the
setTimeout
call callback function. Or there are chances that function variables are being memorized for setTimeout...– Klaider
No, it is only finished when the setTimeout ends its execution.
– Yure Pereira
I don’t think so much because the
setTimeout
is native. But it seems to be the only idea, so...– Klaider
@Klaiderklai variables are not "deleted" but not existing if declared in an internal scope. When there is an asynchronous function like setTimeout active (ie waiting to be executed) the block is kept in memory.
– Sergio