프로그래밍 언어/NODE JS

화살표 함수

· 코딩마이데이
function add1(x, y) {
	return x + y;
}

const add2 = (x, y) => {
	return x + y;
}

const add3 = (x, y) => x + y;

const add4 = (x, y) => (X + y);

function not1(x) {
	return !x;
}

const not2 = x => !x;

 

화살표 함수에서는 function 선언 대신 => 기호로 함수를 선언합니다. 또한, 변수에 대입하면 나중에 재사용할 수 있습니다.

화살표 함수에서 내부에 return문 밖에 없는 경우에는 return 문을 줄일 수 있습니다.

중괄호 대신 return할 식을 바로 적으면 됩니다. add4처럼 보기 좋게 소괄호로 감쌀 수도 있습니다.

매개 변수가 한 개면 매개변수를 소괄호로 묶어주지 않아도 됩니다.

 

var relationship1 = {
	name: 'zero',
	friends: ['nero', 'hero', 'xero'],
	logFriends: function () {
		var that = this; // relationship1을 가리키는 this를 that에 저장
		this.friends.forEach(function (friend) {
 			console.log(that.name, friends);
		});
	},
};
relationship1.logFriends();

 

const relationship2 = {
	name: 'zero',
	friends: ['nero', 'hero', 'xero'];
	logFriends() {
		this.friends.forEach(friend => {
			console.log(this.name, friend);
		});
	},
};
relationship2.logFriends();

 

forEach문에서는 function 선언문을 사용했습니다.

각자 다른 함수 스코프의 this를 가지므로 that이라는 변수를 사용해서 relationship1에 간접적으로 접근할 수 있습니다.

기본적으로 화살표 함수를 쓰되, this를 사용해야 하는 경우에는 화살표 함수와 함수 선언문(tunction) 중에서 하나를 고르면 됩니다.

'프로그래밍 언어 > NODE JS' 카테고리의 다른 글

클래스  (0) 2025.02.09
구조 분해 할당  (0) 2025.02.08
객체 리터럴  (0) 2025.02.06
템플릿 문자열  (0) 2025.02.05
const, let  (0) 2025.02.04