Javascript Arrow function

2024년 01월 25일

화살표 함수(arrow function)

전통적인(?) 자바스크립트 함수는 원래는 이렇게 작성했습니다.

function myFunction(number) {
	return number + 1;
}

그러다 화살표 함수(arrow function)이 등장하게 됩니다.

const myFunction = number => number + 1;

화살표 함수로 함수를 작성하면 훨씬 짧고 간결하게 작성할 수 있습니다. 특히 아래와 같은 경우에는 화살표 함수로 쓰면 코드의 가독성에도 도움이 됩니다.

const myArray = [1, 2, 3];

//화살표 함수로는 매우 간결하지만
myArray.map(num => num+1)

//이렇게 쓰면 복잡하죠
myArray.map(function(num) {
	return num + 1
})

화살표 함수 작성법

화살표 함수를 작성하는 2가지 방법이 있습니다.

  1. 짧은 버전
const myFunction = number => number + 1;
  • 짧은 버전의 함수 body는 1개의 표현식(expression)이어야합니다.
  • 그리고 자동으로 그 1개의 표현식이 return 됩니다.
const myFunction = number => return number + 1;

*return 을 적을 경우 에러가 납니다. retrun이 포함된 경우 표현식이 아닌 명령문이 되기 때문입니다.

const myFunction = number => ( 
	number + 1
);

( )로 감싸는 건 괜찮습니다. ( ) 괄호를 감싸면 여전히 표현식이지만 줄 내림을 할 수 있는 등 코드 포매팅을 할 수 있게 됩니다.

  1. 긴 버전
const myFunction = number => {
	return number + 1;
};
  • 괄호안에 명령문 혹은 명령문 조합이 올 수 있습니다.
  • return을 원하는 경우 return 코드를 작성해야합니다.

화살표 함수 매개변수

매개변수가 1개인 경우 : 아래 2가지 방법 모두 가능합니다.

const myFunction = num => {
	return number + 1;
};

const myFunction = (num) => {
	return number + 1;
};

매개변수가 2개 이상인 경우 : 매개변수가 괄호로 묶여져 있어야합니다.

const addAB = (a, b) => {
	return a + b;
};

매개변수가 없는 경우 : 빈 괄호를 표시해야합니다

const consoleHui = () => {
	console.log("hi");
};

유의사항

화살표 함수는 전통적인 함수 표현에서 형태만 바꾼 것 같지만 사용할 때 몇가지 주의해야할 사항이 있습니다.

1 arrow function의 this

function 함수 표현은 함수의 호출 위치에 따라 this값이 변합니다. 하지만 arrow function은 어디에 쓰이든 this가 바뀌지 않습니다.

const obj = {
	num: 10,
	myFunction() {
		console.log(this, this.num);
	},
	otherObj: {
		num: 20,
	}
}

obj.myFunction();
//{num:10, ...}, 10

const obj2 = obj.otherObj;
obj2.myFunction = obj.myFunction;
obj2.myFunction()
//{num:20, ...}, 20

arrow function의 위치에 상관없이 this는 항상 Window를 가리킵니다.


const obj = {
	num: 10,
	myFunction: () => {
		console.log(this, this.num);
	},
	otherObj: {
		num: 20,
		myFunction: () => {
			console.log(this, this.num);
		}
	}
}

obj.myFunction();
//Window, undefined

const obj2 = obj.otherObj;
obj2.myFunction = obj.myFunction;
obj2.myFunction()
//Window, undefined

2 메서드로 사용할 수 없습니다.

위에서 이야기한 것처럼 화살표 함수는 this가 위치에 따라 변하지 않습니다. 때문에 메서드로 사용할 수 없습니다.

const obj = {
	num: 10,
	myArrowFunction: () => console.log(this, this.num),
	myFunction() {
		console.log(this, this.num);
	}
}

obj.myArrowFunction()
//Window, undefined
obj.myFunction()
//Object, 10

3 생성자로 사용 불가

Arrow function은 생성자로 사용될 수 없습니다. 생성자 함수는 prototype 프로퍼티를 가지고 prototype 프로퍼티가 가리키는 프로토타입 객체의 constructor를 사용하는데, Arrow function은 prototype 프로퍼티가 없습니다.

const consoleHi = () => {console.log('hi')};
consoleHi.hasOwnProperty('prototype'); //false
const hi = new consoleHi(); // Uncaught TypeError: consoleHi is not a constructor

function consoleHellow() {console.log('hi')};
consoleHellow.hasOwnProperty('prototype'); //true
const hello = new consoleHellow(); //ok

위의 이런 특징들은 Arrow function이 Lexical Scope(렉시컬 스코프)를 따르기 때문입니다. 함수가 호출되는 시점이 아니라 정의되는 시점에 고정으로 Window의 scope를 가집니다.


TAGS
JAVASCRIPT