Are the escaped variables deleted even in JavaScript?

3

In JavaScript, whenever the block of a variable scope executes, all its variables are deleted (as they say around the site) ...

(function() {
    var a = false;
})()

But then why when I call setTimeout to alert the value of a variable still recognizes? That is, the variables are not deleted?

(function() {
    var a = true;
    setTimeout(function() {
        alert(a)
    }, 1000);
})()
    
asked by anonymous 12.06.2016 / 02:01

1 answer

3

In 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 for all 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 accessible only within that function.

For example:

function funcOne() {

   var variavelLocal = 10;

   alert(variavelLocal);
}

function funcTwo() {
   alert(variavelLocal + 10);//Um erro será lançado.
}

funcOne();
funcTwo();

Note: Whenever you create variables in Javascript, consider using the reserved word var , because without its use within the scope of a function, the variables within it 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(); 

Responding to your question, variables defined within the scope of a function are only ceased to exist outside the local scope, which is outside the function, in the global scope, so they are not accessible, but they have always existed within the scope the function where they were defined. When this function is executed and when this function finishes its execution they are deleted until setTimeout is finished.

    
12.06.2016 / 02:25