JavaScript

Scope

WebDevLee 2021. 10. 12. 10:44

이 글은 자바스크립트의  Scope에 관한 개념 및 문법을 정리하기 위해 작성하였습니다.




< Scope >

Scope defines where variables can accessed or referenced.

You can think of scope like the view of the night sky from your window. Everyone who lives on the planet Earth is in the global scope of the stars. The stars are accessible globally.
Meanwhile, if you live in a city, you may see the city skyline or the river. The skyline and river are only accessible
locally in your city, but you can still see the stars that are available globally.

 


< Blocks and Scope >

  • A block is code found inside a set of curly braces { }

 

 


< Global Scope >

In global scope, Variables can be accessed by any code in program.

 

  • Variables are declared outside of blocks (global variables)

 

ex)

const color = 'blue';

function returnSkyColor() => {
	return color;   //   blue
}

console.log(returnSkyColor());   //   blue

 

 


< Block Scope >

In block scope, when a variable is defined inside a block,
it is only accessible to the code within the curly braces { }

 

  • Variables are declare within blocks (local variables)
  • Local variables have higher precedence than global variables.
  • Function parameters are also block scope.

 

ex)

// example 1
function logskyColor() {
	const color = 'blue';
    return color;
}

logSkyColor();   //   blue
console.log(color);   //   ReferenceError: color is not defined

// example 2
let name = 'James';

function showName() {
  let name = 'John';
  console.log(name);
}

console.log(name);   //   James
showName();   //   John
console.log(name);   //   James

// This phenomenon in which the outer variable is shadowed by the inner variable
// due to the same variable name is called variable shadowing.

 

 


< Scope Pollution >

When we have too many global variables that exist in the global namespace or when reuse variables across different scopes.

Global namespace is in our code that contains globally scoped information.   ex) number

 

                                 < If a variable does not need global scope, it shouldn't! >

 

ex)

let num = 50;

function logNum() {
	num = 100;
    console.log(num);
}

logNum();   //   100
console.log(num);   //   100  =>  When we call 'logNum()', num gets reassigned