Javascript17(응용JS_스코프&호이스팅) feat.velopert

min seung moon·2021년 3월 6일
0

Javascript

목록 보기
20/23

Scope & Hoisting

1. Scope

  • 우리가 변수, 함수를 생성할 때 어디서 어디까지 유용한지 범위를 정하는것
  • Global Scope(전역), Function Scope(함수 내), Block Scope({}와 같이 block 내)
  • 하지만 var 로 선언시에는 Block Scope 제한이 없어 Function Scope까지만 허용, 그래서 함수 내에 Block Scope는 Function Scope로 간주
  • 그렇기에 var 대신에 let을 권장
//Global Scope
const value = 'hello!';

function myFunction() {
	console.log('myFunction : ');
	console.log(value);
}

function otherFunction() {
	console.log('otherFunction : ');
	//Function Scope
	const value = 'bye';
	console.log(value);
}

function blockFunction(){
	// Function Scope
	const value = 'bye';
	if(true){
	// Block Scope
	const value = 'world';
	console.log('block Scope : ');
	console.log(value)
}
console.log('function Scope : ');
console.log(value)
}

02. Hoisting

  • 자바스크립에서 아직 선언하지 않은 변수, 함수를 끌어올려서 하용하는 작동 방식
  • 함수 선언 전에 작동을 시켜도 정상 작동 됨
  • JS 엔진이 코드 해석 중에 함수를 끌여올려서 이해
myFunction();
function myFunction() {
	console.log('hello world');
}
//myFunction();

console.log(numbers);
var number = 2; //undefined
//해석
var number;
console.log(numbers);
number = 2;
profile
아직까지는 코린이!

0개의 댓글