[JavaScript] 함수 ✅

parkheeddong·2023년 4월 30일

JavaScript

목록 보기
6/26
post-thumbnail


1. 함수 선언문

함수 선언문을 통해 함수를 정의할 수 있다.

function name(parameter1, parameter2, ... parameterN) {
  // 함수 본문
}

✅ Example

function multiply(x, y) {
    return x*y;
}


2. 함수 표현식 (= 함수 리터럴)

함수를 생성하고 변수에 할당하는 방식이다.

let func = function(arg1, arg2, ...argN) {
  return expression;
};

✅ Example

const multiplyTwo = function(x,y) {
    return x*y;
}


3. 화살표 함수

화살표 함수는 함수 표현식보다 단순하고 간결한 문법으로 함수를 만들 수 있는 방법이다.

let func = (arg1, arg2, ...argN) => expression

✅ Example

const multiply_a = (x, y) => {
    return x*y;
}

🌱 간결한 버전

const multiply3 = (x, y) => x*y;
const multiply4 = x => 2*x;



✨ arguments keyword

arguments는 이터러블 객체로서, 인덱스를 사용해 인수에 접근할 수 있다.

const multiplyThree = function(x, y, z) {
    console.log(arguments);
    return x*y*z;
}

console.log(multiplyThree(4,5,6)); 
// [Arguments] { '0': 4, '1': 5, '2': 6 }

✅ 파라미터를 무한하게 받고 싶을 때 활용할 수도 있다..!

const multiplyAll = function(...arguments) {
    // parameter를 무한하게 받고 싶을 때 ...arguments 
    return Object.values(arguments).reduce((a, b)=> a*b, 1);
}


👀 함수는 객체이다!

console.log(typeof multiply); // function
console.log(multiply instanceof Object); 
// multiply가 Object인가? true. 즉 함수는 Object이다. 

0개의 댓글