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'은 한국말로 '돌려주다'입니다. 누가 누구에게 무엇을 돌려준다는 얘기일까요?

  1. 6번 줄을 보시면 inchToCentimeter 함수가 호출됩니다.

  2. inch의 값으로 2가 들어가기 때문에 centimeter에는 2 * 2.545.08이 들어갑니다.

  3. 3번 줄에서 return centimeter를 하기 때문에 inchToCentimeter 함수는 5.08을 '돌려주게' 됩니다.

  4. 함수를 호출한 부분인 inchToCentimeter(2)5.08을 '돌려받아서', inchToCentimeter(2)5.08로 대체된다고 보시면 됩니다. 따라서 result1에는 5.08이 저장됩니다.

7번 줄에도 함수 호출이 있고, 11번 줄에는 함수 호출이 두 개가 있습니다. 콘솔에 7.6215.24가 출력되는 과정 입니다.

Last updated