[1-5] Functions & return

choimarmot·2024년 1월 15일
0
post-thumbnail

바닐라 JS로 크롬 앱 만들기 [1-5] Functions & return


'console.log' 는 그림의 떡, 먹으려면 return이 필요하다!


Function

  • 계속 반복해서 사용할 수 있는 코드 조각
  • 코드를 캡슐화해서 계속 반복가능

예시

적용 전

console.log("Hello my name is Marmot");
console.log("Hello my name is Chris");
console.log("Hello my name is Ada");
console.log("Hello my name is Leon");

문제점 :

  • 이름을 바꾸고 싶으면 직접 다 변경해야 한다.
  • 이름만 다르기 때문에 비효율적

적용 후

function sayHello() {
    console.log("Hello!"); 
}

sayHello();
sayHello();
sayHello();
sayHello();

결과
Hello!
Hello!
Hello!
Hello!

여러 데이터 활용

function sayHello(nameOfPerson, age) {
    console.log("Hello my name is " + nameOfPerson + " and I'm " + age); 
}

sayHello("marmot", 24);
sayHello("chris",34);
sayHello("ada",25);
sayHello("leon", 27); // 각 항목은 Argument

결과
Hello my name is marmot and I'm 24
Hello my name is chris and I'm 34
Hello my name is ada and I'm 25
Hello my name is leon and I'm 27

심화 응용

const player = {
    name: "marmot",
    sayHello: function(otherPersonName){
        console.log("hello " + otherPersonName + " nice to meet you");
    }

};

console.log(player.name); // 결과 : marmot
player.sayHello("chris"); // object = player, function = sayhello

결과
hello chris nice to meet you

'function'을 활용한 계산기

function plus (a, b) {
    console.log(a + b);
}
function divide(a, b) {
    console.log(a / b);
}
plus(5, 7);  // 5, 7은 각각 argument 라고 지칭
divide(9, 3)

결과
12
3

const calculator = {
    add: function (a, b) {
        console.log(a + b);
    }, 
    minus: function (a, b) {
        console.log(a - b);
    },
    times: function (a, b) {
        console.log(a * b);
    },
    divide: function (a, b) {
        console.log(a / b);
    },
    power: function (a, b) {
        console.log(a ** b)
    }
};

calculator.add(5, 5);
calculator.minus(5, 5);
calculator.times(5, 5);
calculator.divide(5, 5);
calculator.power(5, 5);

결과
10
0
25
1
3125

  • NaN : Not a Number
  • a, b -> place holder : 다른 값을 넣어도 작동
  • a라는 값은 function에만 존재하기 때문에 console.log(a); 실행 시 오류 발생

정리 / 강의 요약

  • const 값은 변경 불가, let 사용해서 변경(변경 시 let 안 써도 됨)
  • var 사용 x
  • null -> 값이 비어있다고 하고 싶을 때 사용
  • undefined -> 변수에 값이 없음
  • 배열은 0부터 시작

return

  • 질문에 대한 답 같은 것
  • 작업의 결과를 알려주는 함수가 필요할 때 사용
  • 함수가 어떤 일을 수행하고 그 결과를 알려주는 것
  • 함수 내부에서 'console.log' 하는 것과 달리 외부에서 요청을 받아 값을 반환

예시

나이 계산

const age = 00;
function calculaterKrAge(ageOfForeigner) {
    return ageOfForeigner + 2;
}

const krAge = calculaterKrAge(age);

console.log(krAge);

결과 : 2

함수에 return 적용

const age = 00;
function calculaterKrAge(ageOfForeigner) {
    ageOfForeigner + 2;
    return "hello";
}

const krAge = calculaterKrAge(age);

console.log(krAge);

결과 : hello

함수에 "hello"를 return 하도록 지정하여서 위와 같은 결과 출력

계산기

const calculator = {
    plus: function (a, b) {
        return a + b;
    }, 
    minus: function (a, b) {
        return a - b;
    },
    times: function (a, b) {
        return a * b;
    },
    divide: function (a, b) {
        return a / b;
    },
    power: function (a, b) {
        return a ** b;
    }
};

const plusResult = calculator.plus(2, 3); // 5
const minusResult = calculator.minus(plusResult, 10); // -5
const timesResult = calculator.times(10, minusResult); // -50
const divideResult = calculator.divide(timesResult, plusResult); // -10
const powerResult = calculator.power(divideResult, minusResult);

console.log(timesResult);

결과 : -50

정리 / 강의 요약

  • 변수에 함수를 할당하면 그 변수는 해당 함수의 결과 타입을 가진다.
  • 외부에서 값을 받으려면 return 사용
  • 한번 return 하면 함수는 끝남
    -> return 다음에 console.log("hello"); 추가해도 출력안됨
profile
프론트엔드 개발 일기

0개의 댓글