ammcom
ammcom

Reputation: 1034

Javascript why can I access local variable of function

I am testing this on Google Chrome:

function test(){
    d = 2;
}
function test2(){
    test();
    document.write(d);
}
test2();

The variable d in function test supposed to be local so I cannot access it in function test2, can someone explain why this works?

Edit:

This is not duplicate, as I cannot find anywhere in the correct answer of the original question that using a variable without var makes it global, it is mentioned implicitly as 'horror of implicit globals`

Upvotes: 0

Views: 61

Answers (3)

nurulnabi
nurulnabi

Reputation: 459

When you write d = 2 then you are telling the JavaScript compiler to assign the value 2 to the variable d. The function test will find in its local scope if there variable d is defined or not and it will fail as it has not been declared there. So the test function will ask it's parent scope if that has declared the variable but the parent scope has also not declared the variable d. Then the parent scope of the test function will ask the global scope if that has declared the d and the global scope finds that there's not any variable d hence it will creat a variable named d and return that. As the variable d is declared globally by compiler hence you can access it in test2.

Upvotes: 1

Dabbas
Dabbas

Reputation: 3230

This variable as never been declared, it'll be automatically declared like:

window.d = 2;

Upvotes: 1

SLaks
SLaks

Reputation: 887479

You never actually declared that variable, so it isn't a local variable. Instead, it's an implicit global.

You should always use 'use strict'; to make that an error.

Upvotes: 5

Related Questions