본문 바로가기

Programming/JavaScript

Scope and The Scope Chain

SCOPE CONCENTS

- Scoping: How our program's variables are organized and accessed.

Where do variables live?
Where can we access a certain variable, and where not?

- Lexical scoping: Scoping is controlled by placement of functions and blocks in the code;

- Scope: Space or environment in which a certain variable is declared (variable environment in case of functions). There is global scope, function scope, and block scope;

- Scope of a variable: Region of our code where a certain variable can be accessed.

 

The 3 types of scope

- Global scope

const me = 'Sunny';
const job = 'Technical Writer';
const year = 1988;
  • Outside of any function or block
  • Variables declared in global scope are accessible everywhere

- Function scope

function calcAge(birthYear) {
	const now = 2022;
    const age = now - birthYear;
    return age;
}

console.log(now); // ReferenceError
// function 안에서 declare된 variable이니까 밖에선 access할 수가 없는거임
// now is locally scoped
  • Variables are accessible only inside function. NOT outside
  • Also called local scope

- Block scope (ES6)

if (year >= 1981 && year <= 1996) {
	const millenial = true;
    const food = 'Avocado toast';
}
// Example: if block, for loop block, etc.

console.log(millenial); // ReferenceError
  • Variables are accessible only inside block (block scoped)
  • HOWEVER, this only applies to let and const variables!

-> var로 선언하면 block 밖에서도 accessible함

  • Functions are also block scoped (only in script mode)

 

THE SCOPE CHAIN

 

  • JavaScript engine uses scopes to find out the exact location or accessibility of variables and that particular process is known as Scope Chain.
  • Scope Chain means that one variable has a scope (it may be global or local/function or block scope) is used by another variable or function having another scope (may be global or local/function or block scope).
  • This complete chain formation goes on and stops when the user wishes to stop it according to the requirement.

Scope can be nested

The scope can be nested, which means you can create functions inside another function, block inside another function, function inside another block, or block inside a block.

The scope contained within another scope is named inner scope. And the scope that wraps another scope is named outer scope.

When there are nested scopes, the inner scope can also access the outer scope variables. But outside of the scopes, these variables are not accessible. So outer scope does not have access to the variables of inner functions or blocks.

Scope has access to variables from all outer scopes

VARIABLE LOOKUP IN SCOE CHAIN

inner scope인 second()에서 Global variable인 myName을 access하는 건 가능 🙆‍♀️

but 반대 방향으로는 안됨 🙅‍♀️ ⭐️⭐️⭐️

e.g. 아래 예시에서 first scope은 second scope에 있는 job variable에 access 할 수 없다.

 

const myName = 'Sunny';

function first() {
  const age = 35;

// let and const are block-scoped
  if (age >= 30) {
    const decade = 3;
    var millenial = true;
  }
  // var is function-scoped

  function second() {
    const job = 'technical writer';

    console.log(`${myName} is a ${age}-old ${job}`);
    // Sunny is a 35-old technical writer
  }

  second();
}

first();

여기서 millenial은 if block scope이 아닌 first() scope에 속함

why? var로 선언됐기 때문!

 

What is Scope and Scope Chain in JavaScript? | Simple Explanation with Examples

Simple and step-by-step explanation of Scope and Scope Chain in JavaScript by experts.

dasha.ai

 

Explain Scope and Scope Chain in JavaScript - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

'Programming > JavaScript' 카테고리의 다른 글

Hoisting and The TDZ in Practice  (0) 2022.11.20
Scoping in Practice  (1) 2022.11.19
SCOPE CHAIN VS. CALL STACK  (0) 2022.11.17
The JavaScript Engine and Runtime  (0) 2022.11.16
Execution Contexts and the Call Stack  (0) 2022.11.16