본문 바로가기

자바스크립트

[JavaScript] 37. Reviewing Functions (Declarations, Expressions, Arrows)

JS의 함수의 세 가지 방식(Declarations, Expressions, Arrows)에는 표현만 다르고, 기능은 같습니다.

 

// Function Declaration
// Function that can be used before it's declared
function calcAge(birthYear){
	return 2037 - birthYear;
}


// Function Expression
// Essentially a functio values stored in a variable
const calcAge = function(birthYear){
	return 2037 - birthYear;
}


// Arrow function
// Great for a quick one-line functions.
// Has no THIS KEWORD

 

 

Arrow Functions (화살표 함수)

const yearsUntilRetirement = (birthYear, firstNAme) =>{
	const age = 2037 - birthYear;
	const retirement = 65 - age;
	return `${firstName} retires in ${retirement} years`;
}

 

Function Expressions 함수 선언

const calcAge = function(birthYear){
	return 2037 - birthYear;
}

const yearsUntilRetirement = function (birthYear, firstName) {
	const age = calcAge(birthYear);
	const retirement = 65 - age;

	if (retirement > 0){
		console.log(`${firstName} retires in ${retirement} years`);
		return retirement;
	} else{
	console.log(`${firstName} has already retired`);
		return -1;
	}	
}

console.log(yearsUntilRetirement(1971, 'Ki'))
console.log(yearsUntilRetirement(1991, 'Jonas'))