0

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`

3
  • 4
    if that's the only place d is defined, it's not local. you would need to var d = 2; for it to be a local variable. By your definition, it's global. Commented Dec 27, 2017 at 18:29
  • because one should use var .... Commented Dec 27, 2017 at 18:30
  • @baao this is not duplicate as I cannot find my answer in the alleged duplicate, please check it Commented Dec 27, 2017 at 18:41

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

window.d = 2;

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.