함수를 만드는 방법



함수 선언(Function Declaration)

function 함수이름(파라미터) {
	동작
	return 리턴값
}

함수 표현식 (Function Expression)

// 함수 선언을 값처럼 할당하는 방식
const printApple = function () {
	console.log('Apple');
};

함수 선언과 함수 표현식의 차이

printOrange(); // Orange 

function printOrange() {
	console.log('Orange')
}

printApple(); // ReferenceError

const printApple = function () {
	console.log('Apple');
};

const x = 5;

if (x < 5) {
	function printJS() {
		console.log('JS');
	}
}

{
	function printAdam() {
		console.log('Adam');
	}
}

// 함수 선언은 전역적으로 호출이 된다
printAdam(); 
printJS();

// 함수 표현식은 할당된 변수에 따라 스코프가 결정된다.

var printJS = function() {
	console.log('JS');
}

let printHi = function() {
	console.log('Hi');
}

const printApple = function () {
	console.log('Apple');
}

기명 함수 표현식 (Named Function Expression)


  • 함수 표현식으로 만들 때 선언하는 함수에 이름을 붙일 수 있다.
const printSayHi = function sayHiFunction() {
	console.log('Hi');
	sayHiFunction();
}

// Hi
// Hi


즉시 실행 함수


  • IIFE(Immediately Invoked Function Expression )라 한다.
  • 함수 선언과 동시에 즉시 실행되는 함수
(function (x, y) {
    console.log(x + y);
})(2, 3);

// 5

즉시 실행 함수의 활용

  1. 선언과 동시에 실행이 이뤄지기 때문에 일반적으로 프로그램 초기화 기능에 많이 사용

    (function init() {
    	// 초기화 될때 시작할 코드
    });
  2. 재사용이 필요없는 일회성 동작을 구성할 때 활용

    • 함수의 리턴값을 바로 변수에 할당할떄 사용

      const myName = 'Adam';
      
      const greetingMessage = (function () {
      	return `Hi! My name is ${myName}`;
      });
      // Hi My Name is Adam


값으로서 함수


  • Javascript 에서 함수는 변수나 데이터구조 또는 다른 함수의 파라미터, 리턴값으로 할당되어질 수 있다. ⇒ 일급 함수 (Fisrt Class Function) 이라 한다.

    function makeQuize(quiz, answer, success, fail) {
      if (prompt(quiz) === answer) {
        console.log(prompt('3 + 5'))
        console.log(success());
      } else {
        console.log(fail());
      }
    };
    
    function getSuccess() {
      return 'Right Answer';
    }
    
    function getFail() {
      return 'Wrong Answer';
    }
    
    const question = '5 + 3 = ?';
    
    // 여기서 getSuccess(), getFail()함수는 콜백 함수이다.
    makeQuize(question, '8', getSuccess, getFail);

콜백함수

  • 다른 함수의 파라미터로 전달된 함수

고차 함수

  • 함수를 리턴함수에서 리턴된 함수를 바로 호출하여 사용하는 함수

    function getPrintHi() {
      return function () {
        console.log('Hi');
      }
    }
    
    // 고차함수
    getPrintHi()();

Parameter And Argument


  • Parameter : 함수 선언 부분에서 소괄호 부분에 해당하는 부분 ⇒ function greeting(name) { }

  • Argument : 함수를 호출하는 부분에서 Parameter로 전달하는 부분 ⇒ greeting('Adam')

  • 함수의 기본 값

    • 기본값 지정할 수 있다. : function greeting(name = 'adam')

    • undefine 으로 기본값을 이용가능하다.

      function greeting(name = 'adam', age = 29) {
        console.log(`Hi my name is ${name}`);
        console.log(`I'am ${age} old`);
      }
      
      greeting(undefined, 30)
      
      // Hi my name is adam
      // I'am 30 old
  • 다른 파라미터를 이용하여 함수를 선언할 수 있다.

    function numSum(x, y = x + 2) {
      console.log(x)
      console.log(y)
    }
    
    numSum(2)
    
    // 2
    // 4

Arguments 객체

  • 함수에 전달된 arguments 들을 arguments 객체로 다룰 수 있다.

    function printArguments(a, b, c) {
      for (let arg of arguments) {
        console.log(arg)
      }
      console.log('-----------')
    }
    
    printArguments('Adam', 'Eve', 'Json', 'Jesus')
    
    // Adam
    // Eve
    // Json
    // Jesus

Rest Parameter

  • arguments 유사배열 객체와는 다르게 유연하게 arguments 들을 다룰 수 있는 배열 객체
  • 일반 argument 와 같이 쓸 수 있다. (하지만 rest parameter는 가장 마지막에 써야된다.)
    function printRank(first, second, ...others) {
      console.log('Ranking');
      console.log(`우승 : ${first}`);
      console.log(`준우승 : ${second}`)
      for (const arg of others) {
        console.log(`참가자 : ${arg}`)
      }
    }
    
    printRank('Adam', 'Eve', 'Lay', 'Json', 'Emil')
    
    // Ranking
    // 우승 : Adam
    // 준우승 : Eve
    // 참가자 : Lay
    // 참가자 : Json
    // 참가자 : Emil


Arrow Function



함수 선언을 더욱 간결하게 표현한 익명 함수


// 일반적인 함수 선언
const getTwice = function (number) {
  return number * 2
}

// Arrow Function 을 이용하여 작성
const getTwice = (number)  => {
  return number * 2
}

// 파라미터가 하나인 함수는 소괄호()를 생략 할 수 있다.
const getTwice = number => {
	return number * 2
}

// 내부의 동작이 리턴문 한문장이라면 중괄호{}와 return문을 생략 할 수 있다.
const getTwice = number => number * 2

// 객체를 리턴한다면 소괄호를 감싸주어야된다. (함수의 동작부분으로 인식하기 때문)
const getName = () => ({ name : 'Adam'});

// Arrow Function 에서는 arugments 객체를 사용할 수 없다.
const getArg = () => {
	console.log(arguments); 
};
getArg(1, 2, 3);  // Uncaught Error


This 객체



This 는 함수를 호출한 객체를 가리키는 키워드


console.log(this);
// 기본 this 값 호출
// Window {window: Window, self: Window, document: document, name: '', location: Location, …}

function printThis() {
  console.log(this)
}

const myObj = {
  content: 'myObj',
  printThis: printThis,
}

const otherObj = {
  content: 'otherObj',
  printThis: printThis,
}

myObj.printThis();
otherObj.printThis();

// 함수를 호출한 객체를 프린트
// {content: 'myObj', printThis: ƒ}
// {content: 'otherObj', printThis: ƒ}


Arrow Function에서의 this는 Arrow Function이 선언되기 직전의 객체를 가리켜, this를 사용할 때는 일반함수를 권장한다.


console.log(this);

// Arrow Function의 This 이 선언되기 직전인 Window객체를 가리킨다.
const printThis = () => {
  console.log(this)
}

const myObj = {
  content: 'myObj',
  printThis: printThis,
}

const otherObj = {
  content: 'otherObj',
  printThis: printThis,
}

myObj.printThis();
otherObj.printThis();

// Window {window: Window, self: Window, document: document, name: '', location: Location, …}
// Window {window: Window, self: Window, document: document, name: '', location: Location, …}
// Window {window: Window, self: Window, document: document, name: '', location: Location, …}