05-1. return:돌려주다
미국 단위인 '인치(inch)'를 '센티미터(cm)'로 변환 시켜주는 함수 inchToCentimeter를 작성했습니다.
function inchToCentimeter(inch) {
var centimeter = inch * 2.54; // 1 inch = 2.54cm
return centimeter; // cm로 계산한 결괏값 돌려주기
}
var result1 = inchToCentimeter(2); // 2 inch를 cm로 바꾼 값
var result2 = inchToCentimeter(3); // 3 inch를 cm로 바꾼 값
console.log(result1);
console.log(result2);
console.log(inchToCentimeter(1) + inchToCentimeter(5));결과)
5.08
7.62
15.24코드를 보면 return이라는 게 있죠? 'return'은 한국말로 '돌려주다'입니다.
누가 누구에게 무엇을 돌려준다는 얘기일까요?
6번 줄을 보시면
inchToCentimeter함수가 호출됩니다.inch의 값으로2가 들어가기 때문에centimeter에는2 * 2.54인5.08이 들어갑니다.3번 줄에서
return centimeter를 하기 때문에inchToCentimeter함수는5.08을 '돌려주게' 됩니다.함수를 호출한 부분인
inchToCentimeter(2)는5.08을 '돌려받아서',inchToCentimeter(2)가5.08로 대체된다고 보시면 됩니다. 따라서result1에는5.08이 저장됩니다.
7번 줄에도 함수 호출이 있고, 11번 줄에는 함수 호출이 두 개가 있습니다.
콘솔에 7.62와 15.24가 출력되는 과정 입니다.
Last updated
Was this helpful?