Javascript | Scope

YEONG·2023년 6월 4일
0

javascript

목록 보기
1/1
post-thumbnail

If I should have supernatural powers, I would have the ability to never forget what I've seen. I try to recall a memory about that I studied before, it remains dimly in my memory. I've seen about that but it is hard to explain. That's why I studied about Javascript again. Rather than studying it from A to Z, I will focus on topics that are important or cannot be clearly explained. Anyway, the topic I wrote about today is the scope.

The scope is very important concept to understand how Javascript works and it is related to function, excution context and variable. If there is a example like below, what is the result of x?

var x = 'global';

function foo() {
	var x = 'local';
    console.log(x); // 1
}

foo();

console.log(x); // 2

In case of 1, x is printed as 'local', and in case of 2, x is printed as 'global'. The two results are different because of identifier resolution. If there are same variables, Javascript engine has to decide which one to use. The JavaScript engine determines which one to use based on where these variables are declared.

Scopes can be classified into two types: local scope and global scope. Local scope is space inside a function. It is possible to get a nested local scopes because funtion can be declared inside of function. Scopes are chained from local scope that is located at the bottom to global scope. So Javascript engine starts searching from the innermost local scope. For this reason, x is printed as 'local' in case of 1.

However, in below case, what is the result of 1 and 2? It is a question of what the parent scope of bar is. Depending on the programming language, the way of defining scope is different. On one hand, scope is defined when function is called(dynamic scope). On the oher hand, scope is defined depending on where the function is defined(lexical scope). Javascript works in the lexical scope way. So, all of them are printed 1, because function bar is declared on global scope.

var x = 1;

function foo() {
  var x = 10;
  bar();
}

function bar() {
  console.log(x);
}

foo(); // 1
bar(); // 2

Reference

0개의 댓글