TIL - JavaScript - Scope

홍예찬·2020년 7월 26일
0
post-thumbnail

1. Scope

1-1. Global Scope

변수가 블록 바깥에 위치해서 블록 내 코드뿐만 아니라 다른 코드에도 접근할 수 있다.

const satellite = 'The Moon';
const galaxy = 'The Milky Way';
const stars = 'North Star';
function callMyNightSky() {
  return 'Night Sky: ' + satellite + ', ' + stars + ', and ' + galaxy;
};
console.log(callMyNightSky());
//Output: Night Sky: The Moon, North Star, and The Milky Way

1-2. Block Scope

블록 안에 위치하기 때문에 그 코드에서만 기능.

const logVisibleLightWaves = () => {
  const lightWaves = 'Moonlight';
  console.log(lightWaves);
};
console.log(logVisibleLightWaves());
console.log(lightWaves);
/*Output: Moonlight
          undefined
          ReferenceError: lightWaves is not defined

1-3. Scope Pollution

코드 바깥의 변수 선언과 함수 블럭 내에 재할당된 변수가 같이 있을 경우, 코드 내부의 재할당된 변수가 작동된다.

const satellite = 'The Moon';
const galaxy = 'The Milky Way';
let stars = 'North Star';

const callMyNightSky = () => {
  stars = 'Sirius';
	return 'Night Sky: ' + satellite + ', ' + stars + ', ' + galaxy;
};

console.log(callMyNightSky()); 
//Output: Night Sky: The Moon, Sirius, The Milky Way
console.log(stars);
//Output: Sirius

//반면 두 순서를 바꿀 경우

console.log(stars);
//Output: North Star
console.log(callMyNightSky()); 
//Output: Night Sky: The Moon, Sirius, The Milky Way

1-4. Good Scoping

const logVisibleLightWaves = () => {
	let lightWaves = 'Moonlight';
	let region = 'The Arctic';
		if (region === 'The Arctic') {
  		let lightWaves = 'Northern Lights';
    	console.log(lightWaves);
  		}
	console.log(lightWaves);
	};

logVisibleLightWaves();
/*Output: Northern Lights
          Moonlight 
*/
profile
내실 있는 프론트엔드 개발자가 되기 위해 오늘도 최선을 다하고 있습니다.

0개의 댓글