AL-zami
AL-zami

Reputation: 9066

why if statement isn't looking for a variable in global scope

I am trying to understand scoping in JS.Here i have an example which has a variable in global scope called check.It has a truthy value i mean 1.Then inside a function called main which doesn't have a variable called check but has an if statement which checks whether there is a check variable or not ,upon which it reassign another value to check variable.Then prints it out.if i use

if(check){}

it prints undefined.Here i have some questions:

1. check variable is declared in global scope.It means it has access everywhere.Then even if the IF statement fails it should print the globally assigned value which is 1 instead of undefined.Why it prints undefined instead of 1??

2. main function scope doesn't have a check variable.When if fails to find check inside main function's scope ,why it doesn't look for it in global scope??

  (function(){
        var check=1;
        function main(){
		    if(check){
               var check=10;
	        }
			document.write(check);
			}
		main();
    })();

Upvotes: 0

Views: 141

Answers (2)

TGH
TGH

Reputation: 39258

JavaScript will look up the chain for the most local variable it can find. Basically, local scope trumps global scope.

This is one of the potential pitfalls with global scope, and is why it should be avoided, since it creates clashes with local variables.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816472

JavaScript only has function scope and something called hoisting. Every variable declaration inside a function gets put at the beginning of the function. Thus, your code is equivalent to

var check=1;
function main(){
  var check; // = undefined
  if(check){ // block doesn't create scope
    check=10;
  }
  document.write(check);
}

The local variable check shadows the outer variable check.

Upvotes: 4

Related Questions