[JavaScript] Koans | 스코프(scope), 화살표 함수(Arrow function)

Eunji Lee·2022년 11월 9일
0

[TIL] JavaScript

목록 보기
11/22
post-thumbnail

스코프(scope)

변수의 값(변수에 담긴 값)을 찾을 때 확인하는 곳

함수 호이스팅(hoisting)

  • 호이스팅(hoisting): 인터프리터가 변수와 함수의 메모리 공간을 선언 전에 미리 할당함
    • var로 선언한 변수: 호이스팅 시 undefined로 변수를 초기화함
    • let과 const로 선언한 변수: 호이스팅 시 변수를 초기화하지 않음
      → 함수의 코드를 실행하기 전에 함수 선언에 대한 메모리부터 할당하기 때문에 함수 호출을 함수 선언보다 앞에 적을 수 있음
let funcExpressed = 'to be a function';
console.log(typeof(funcDeclared)); //'function'
console.log(typeof (funcExpressed)); //'string'

function funcDeclared() {
	return 'this is a function declaration';
}

funcExpressed = function () {
	return 'this is a function expression';
}; //재할당

const funcContainer = { func: funcExpressed };
console.log(funcContainer.func());// 'this is a function expression'

funcContainer.func = funcDeclared;
console.log(funcContainer.func());//'this is a function declaration';

cf) console.log(funcContainer.func)의 경우, funcExpressed함수 자체가 리턴됨
cf) console.log(funcContainer.func)의 경우도 마찬가지로 funcDeclared 함수 자체가 리턴됨

클로저(Closure)

  • 함수와 함수가 선언된 어휘적 환경(lexical scope)의 조합이며, 어휘적 환경은 클로저가 생성된 시점의 유효 범위 내에 있는 모든 지역 변수로 구성됨
let age = 27;
let name = 'jin';
let height = 179;

function outerFn() {
	let age = 24;
	name = 'jimin';
	let height = 178;

	function innerFn() {
		age = 26;
		let name = 'suga';
      	console.log(name); //'suga'
		return height;
  }

  innerFn();

  console.log(age); //26
  console.log(name); //'jimin'

  return innerFn;
}

const innerFn = outerFn();

console.log(age); //27
console.log(name); //'jimin'
console.log(innerFn()); //'suga' 다음에 178이 출력됨



화살표 함수(Arrow function)

함수 표현식

호이스팅에 영향을 받음
cf) 함수 선언식: 호이스팅에 영향을 받지 않음

const add = function (x, y) {
	return x + y;
}

console.log(add(10, 5)); //15

화살표 함수

const add = (x, y) => {
	return x + y;
}
console.log(add(10, 5)); //15

// 리턴을 생략하기
const subtract = (x, y) => x - y;
console.log(subtract(15, 20)); //-5

// 필요에 따라 소괄호를 붙일 수도 있음
const multiply = (x, y) => (x * y);
console.log(multiply(5, 6)) //30

// 파라미터가 하나일 경우 소괄호 생략 가능
const divideBy2 = x => x / 2;
console.log(divideBy2(43)); //21.5

0개의 댓글