김숭늉 마음대로

자바스크립트 함수 표현식과 선언식 화살표함수, 함수안에서 함수 사용하기 본문

IT/JavaScript

자바스크립트 함수 표현식과 선언식 화살표함수, 함수안에서 함수 사용하기

김숭늉이 2023. 9. 13. 11:15
728x90

 

함수 declaration 선언식 - 호이스팅에 영향을 받음

 

[선언방식]

const 함수이름 = function (){

 return 구현로직

}

//function declaration
function calcAge1(birthYear) {
return 2037 - birthYear;
}
const age1 = calcAge1(1991);
 

 


function fruit(apples, oranges) {
const juice = `juice with ${apples} apples and ${oranges} oranges`;
return juice;
}

const appleJuice = fruit(3, 5); // arguments
console.log(appleJuice);

const appleOrangeJice = fruit(2, 4);
console.log(appleOrangeJice);

 

함수 expression 표현식 - 호이스팅에 영향을 받지 않음

[선언방식]

var 함수이름 = function(){

 구현로직 


//function expression

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

const age2 = calcAge2(1991);

console.log(age1, age2);

 

es6에 새로 추가된 함수 기능(화살표 함수) 

중괄호 필요없고 반환이 자동으로 일어남, reture 키워드를 쓸 필요가 없음 

const calcTips = function (bill) {
return bill >= 50 && bill >= 300 ? bill * 0.15 : bill * 0.2;
}; // 기본식

const calcTip = (bill) =>
bill >= 50 && bill >= 300 ? bill * 0.15 : bill * 0.2; // 화살표함수

 

const calcAge2 = function (birthYear) {
return 2037 - birthYear;
}; // 기본식

const calcAge3 = birthYear => 2037 - birthYear; //화살표함수

 

화살표 함수더라도 여러줄이면 리턴 키워드를 사용해야함

 
 
const yearUntilRetirement = (birthYear) => {
const age = 2037 - birthYear;
const retirement = 65 - age;
return retirement;
};

console.log(yearUntilRetirement(1991));

 

화살표함수에서 매개변수가 여러개인경우는? 괄호안에 중복으로 작성함

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

console.log(yearUntilRetirement(1991, "seungyeon"));
console.log(yearUntilRetirement(1989, "minhyeok"));

 

 

함수 안에서 다른 함수를 호출할경우 - 아주 흔한 케이스임 

dry 코드를 위해 많이 씀 

// console.log(yearUntilRetirement(1989, "minhyeok"));

function cutFruitPieces(fruit) {
return fruit * 4;
}

function fruitProcessor(apples, oranges) {
const applePieces = cutFruitPieces(apples);
const oragepieces = cutFruitPieces(oranges);

const juice = `juice with ${applePieces} apples and ${oragepieces} oranges`;
return juice;
}

console.log(fruitProcessor(2, 3));

 

 


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

const yearUntilRetirement = (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(yearUntilRetirement(1991, "seungyeon"));
console.log(yearUntilRetirement(1950, "seungyeon"));

옴션 + 화살표방향키 위 누르면 코드가 한줄 위로 이동함 

리턴이 있으면 함수가 종료됨  !

 

 

const calcAverage = (a, b, c) => (a + b + c) / 3; // return 을 쓸필요도 없음
console.log(calcAverage(3, 4, 5));

// test 1
let scoreDolphins = calcAverage(44, 23, 71);
let scoreKoalas = calcAverage(65, 54, 49);
console.log(scoreDolphins, scoreKoalas);

const checkWinner = function (avgDolphins, avgKoalas) {
if (avgDolphins >= 2 * avgKoalas) {
console.log(`Dolphins win! (${avgDolphins} vs ${avgKoalas})`);
} else if (avgDolphins * 2 <= avgKoalas) {
console.log(`Koalas win! (${avgDolphins} vs ${avgKoalas})`);
} else {
console.log("No team wins...");
}
};

checkWinner(scoreDolphins, scoreKoalas); // No team wins...
checkWinner(555, 111); //Dolphins win! (555 vs 111)

// test 2
scoreDolphins = calcAverage(85, 54, 41);
scoreKoalas = calcAverage(23, 34, 27);
console.log(scoreDolphins, scoreKoalas);
checkWinner(scoreDolphins, scoreKoalas);

 

728x90
반응형