함수 function

DOYOUNG·2023년 5월 17일
0

javascript

목록 보기
8/17
post-thumbnail

자바스크립트 함수

함수는 반복될 수 있는 작업을 미리 정의해두는 것이다.
input을 받아 output을 반환(return)한다.

1. 함수의 기본 문법과 형식

function add(x, y) { // x,y : 매개변수(parameter), 인자
  return x + y; // ⭐️ 값을 반환
  // 특정 값을 반환하는 함수는 return문 필요함
}

let z = add(2, 3); // 2,3 : 인수

console.log(z); // 5
function isOdd (x) {
  return !!(x % 2);
}

let num = 12;

console.log(
  `${num}(는)은 ${
    isOdd(num) ? '홀' : '짝'
  }수입니다.`
);
  • 좋은 함수는 인자가 있는 것이다. function(인자) {}
  • 함수에서 return 문을 사용할 때는 가장 아래에 쓰기.
    return 보다 아래에 있는 것은 실행되지 않음.

📌 return문 없어도 실행 가능함

let currentTemp = 24.5;

function logCurrentTemp () {
  console.log(`현재 온도는 섭씨 ${currentTemp}도입니다.`);
}

console.log('반환값:', logCurrentTemp());

return 문이 정의되어 있지 않으면 undefined 반환함
👉 console.log 실행 뒤 undefined가 뜨는 이유

⭐️ 호이스팅 hoisting

함수는 실행문보다 나중에 정의하는 것이 가능함
변수나 상수는 불가능(var 제외)하고 오직 함수만 가능.

console.log(add(2, 7));

function add (x, y) {
  return x + y;
}

2. 함수 정의 방법

1) 함수 선언 (호이스팅 O)

오직 function으로 선언된 함수만 호이스팅 된다. 엔진의 코드 실행 전에 미리 생성되기 때문이다.

function add (x, y) {
  return x + y;
}

console.log(add(2, 7));

2) 상수나 변수에 함수 대입 (함수도 값) (호이스팅 X)

const subt = function (x, y) {
  return x - y;
}

console.log(subt(7, 2));

기존 함수를 재정의하는 것도 가능함

function add (x, y) {
  return x + y;
}

console.log(add(2, 7));

// 💡 기존의 함수를 재정의하는것도 가능
add = function (x, y) {
  console.log(`${x}${y}를 더합니다.`);
  console.log(`결과는 ${x + y}입니다.`);
  return x + y;
}

console.log(add(2, 7));

3) 화살표 함수

// 한 줄 안에 값만 반환시
const mult = (x, y) => x * y;

console.log(mult(2, 7));
// 두 줄 이상의 작업이 있을 시
const mult = (x, y) => {
  console.log(`${x}${y}를 곱합니다.`);
  console.log(`결과는 ${x * y}입니다.`);
  return x * y; // return 필수
};

console.log(mult(2, 7));
// 인자가 하나일 때는 괄호 없이 선언 가능
const pow = x => x ** 2;
console.log(pow(3));

❗️블록문에 들어가는 화살표 함수는 return 문 필수❗️
화살표 함수는 function 으로 선언된 함수와 기능 차이가 있음

3. 일급 객체 First Class Object

함수를 변수와 같이 다루는 개념이며 자바스크립트의 함수는 객체로 본다.

// ⭐️ 함수의 자료형
function addNumbers (a, b) { return a + b; }
console.log(typeof addNumbers); // function

1) 상수 또는 변수에 할당될 수 있음

  • 상수나 변수에 할당된 경우
function isOddNum (number) {
  console.log(
    (number % 2 ? '홀' : '짝')
    + '수입니다.'
  );
  return number % 2 ? true : false;
};

const checkIfOdd = isOddNum; // 뒤에 괄호 없음 유의

console.log(checkIfOdd(23));
let x = 7, y = 3;

let func1 = (a, b) => a + b;
let func2 = (a, b) => a - b;
console.log(func1(x, y), func2(x, y));

func1 = func2
console.log(func1(x, y), func2(x, y));
  • 객체나 배열의 값으로 할당된 경우
let person = {
  name: '홍길동',
  age: 30,
  married: true,
  introduce: function (formal) {
    return formal
    ? '안녕하십니까. 홍길동 대리라고 합니다.'
    : '안녕하세요, 홍길동이라고 해요.';
  }
};

console.log(person.introduce(true));
console.log(person.introduce(false));
let person = {
  name: '홍길동',
  age: 30,
  married: true,
  introduce: function () {
    return `저는 ${this.name}, ${this.age}살이고 `
    + `${this.married ? '기혼' : '미혼'}입니다.`;
  }
}

console.log(person.introduce());

객체의 다른 프로퍼티에 접근할 때 : this 사용함.
📌 객체 리터럴의 프로퍼티에 this를 사용할 때는 화살표 함수를 권장하지 않음.

let arithmetics = [
  (a, b) => a + b,
  (a, b) => a - b,
  (a, b) => a * b,
  (a, b) => a / b
];

for (arm of arithmetics) {
  console.log(arm(5, 3));
}

2) 다른 함수에 인자로 전달될 수 있음 (고차함수, 콜백함수)

함수가 다른 함수를 인자로 전달받음

  • 전달받는 함수 : 고차 함수 highter-order function
  • 전달되는 함수 : 콜백 함수 callback function
let list = [1, 2, 3, 4, 5];

function doInArray (array, func) {
  for (item of array) {
    func(item);
  }
}

// console.log - console이란 객체에서 log란 키에 할당된 함수
doInArray(list, console.log);

doInArray : 고차함수
console.log : 콜백함수

function doNTimes (func, repeat, x, y) {
  let result = x;
  for (i = 0; i < repeat; i++) {
    result = func(result, y);
  }
  return result;
}

console.log(
  doNTimes((x, y) => x * y, 3, 5, 2),
  doNTimes((x, y) => x / y, 3, 5, 2),
);
  • 인자로 전달된 함수 : 익명 함수 anonymous function
    변수나 상수에 할당되지 않아 이름이 없음
// calculate
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
const multiply = (a, b) => a * b;

// evaluate
const isOdd = (number) => !!(number % 2);
const isPositive = (number) => number > 0;

function calcAndEval (calc, eval, x, y) {
  return eval(calc(x, y));
}

console.log(
  calcAndEval(add, isOdd, 5, 7),
  calcAndEval(subtract, isPositive, 5, 7),
  calcAndEval(multiply, isOdd, 5, 7)
);

3) 다른 함수의 결과값으로서 반환될 수 있음

function getIntroFunc (name, formal) {
  return formal
  ? function () {
    console.log(`안녕하십니까, ${name}입니다.`);
  } : function () {
    console.log(`안녕하세요~ ${name}이라고 해요.`);
  }
}

const hongIntro = getIntroFunc('홍길동', true);
const jeonIntro = getIntroFunc('전우치', false);

hongIntro();
jeonIntro();

📌 커링 currying

필요한 인자보다 적은 수의 인자를 받으면, 나머지 인자를 인자로 받는 다른 함수를 반환함.

// 기존의 코드
function addMultSubt (a, b, c, d) {
  return (a + b) * c - d;
}

const addMultSubt2 = (a, b, c, d) => (a + b) * c - d;

console.log(
  addMultSubt(2, 3, 4, 5),
  addMultSubt2(2, 3, 4, 5),
);
// ⭐ 커링으로 작성된 함수
function curryAddMultSubt (a) {
  return function (b) {
    return function (c) {
      return function (d) {
        return (a + b) * c - d;
      }
    }
  }
}

const curryAddMultSubt2 = a => b => c => d => (a + b) * c - d;

console.log(
  curryAddMultSubt(2)(3)(4)(5),
  curryAddMultSubt2(2)(3)(4)(5)
);
profile
프론트엔드 개발자 첫걸음

0개의 댓글