[NodeJS] 자바스크립트 함수 종류

Onam Kwon·2023년 5월 31일
0

Node JS

목록 보기
24/25

자바스크립트 함수 종류

  • 제가 자바스크립트라는 언어를 처음 접했을 때 C++나 Python을 만지다가 온 입장에서 함수 제작 문법이 특이하다 생각되어 따로 정리를 해보겠습니다.
  • 아래는 자바스크립트 함수 종류 입니다.
  • Named Functions
  • Anonymous Functions
  • Arrow Functions
  • Immediately Invoked Function Expressions (IIFE)
  • Higher Order Functions
  • Constructor Functions

1. Named Functions

/**
 * 1. Named functions.
 * Traditional way.
 */
function myFunction() {
    console.log('This function is called named function.');
}
myFunction(); // This function is called named function.
  • 제일 기본적인 형태의 함수로 다른 프로그래밍 언어에서도 위의 형식으로 보통 사용합니다.

2. Anonymous Functions

/**
 * 2. Anonymous functions.
 * Without name, used as function expression or arguments.
 */
let greet = function(name) {
    console.log(`Hello, ${name}!`);
}
greet('Five'); // Hello, Five!
  • Anonymous는 익명의 라는 뜻을 가진 영어 단어로 자바스크립트에선 함수의 이름을 명시하지 않고 정의할 때 사용할 수 있습니다.
  • 위와 같이 변수에 담아 사용할 수 있으며 함수를 호출 할 때 처럼 매개변수도 함께 사용할 수 있습니다.

3. Arrow Functions

/**
 * 3. Arrow functions.
 * Arrow functions introduced in ES6, shorter syntax & one lined functions.
 */
let greetWithArrow = () => console.log('Hello');
greetWithArrow(); // Hello
  • 화살표 함수라고 부르며 전통적인 함수의 간편한 대안이지만, 몇가지 제한점이 있고 모든 상황에 사용할 수는 없습니다. 이에 관해선 따로 다뤄 보도록 하겠습니다.

4. Immediately Invoked Function Expressions (IIFE)

/**
 * 4. Immediately Invoked Function Expressions (IIFE).
 * Executed immediately after their creation. Used to create private scopes and avoid polluting the global namespace.
 */
(function () {
    let greeting = 'How are you doing?';
    console.log(greeting);
})();
  • 생성 직후 바로 실행되며, 별도의 scope 를 만들어 global namespace에 영향을 주지 않기 위해 사용됩니다.

5. Higher Order Functions

/**
 * 5. Higher Order Function.
 * Functions that take one or more functions as arguments or return a function.
 * eg: map(), filter(), reduce()
 */
let arr = [10, 20, 30];
let twiced = arr.map((element) => element * 2);
console.log(twiced); // [20, 40, 60]
  • 한개 이상의 함수를 인수로 사용하거나 함수를 반환하는 함수.

6. Constructor Functions

/**
 * 6. Constructor Function.
 * Used as blueprints for creating objects with similar properties and methods.
 * They are invoked using the new keyword to create instances of objects.
 */
function Person(name, place) {
    this.name = name;
    this.place = place;
}
let user1 = new Person('Five', 'Heaven');
let user2 = new Person('Ten', 'Hell');
console.log(`Hello everyone, this is ${user1.name}, and I am from ${user1.place}.`);
console.log(`Hello everyone, this is ${user2.name}, and I am from ${user2.place}.`);
  • 비슷한 속성과 메소드를 가진 객체를 만들기 위한 설계도로 사용합니다.
  • new 키워드를 사용해 해당 함수를 호출할 수 있으며, 새로운 객체를 생성할 때 사용합니다.

github

profile
권오남 / Onam Kwon

0개의 댓글