5. 함수

jean·2021년 2월 7일
0
post-thumbnail

자바스크립트에 최근에 추가된 class는 java처럼 pure한 oop가 아니라 프로토 타입을 베이스로 한 가짜 oop이다. 따라서 자바스크립트도 procedural language 중의 하나이다.

procedural language에서는 함수가 프로그램에서 중요한 역할을 담당한다.
따라서 때로는 function을 program 안에서 각각의 작은 단위들을 수행하는 sub-program이라고 부르기도 한다.

하나의 함수는 한 가지의 일만 하도록 만들어야 한다.
함수의 이름 = doSomething, command, verb 같이 동사의 형태로 지정한다.

function is object in JS (변수 할당, 인수로 전달, 리턴값)

자바스크립트는 Type이 없으므로 데이터 타입을 예상하기 어렵다.

TypeScript

  1. SypeScript Playground에서 왼편에 타입스크립트를 작성하면 오른쪽에 자바스크립트 버전을 확인할 수 있다.

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAGzgcwBQFsCmBnPAQzRwC5E8oAnGMNASkQG8AoRdxCBPOZHAOlSZcBYjnoBuFgF8gA

  1. parameters
    // premitive parameters: passed by value
    // object parameters: passed by reference

premitive data type은 메모리에 value가 그대로 저장돼 있기 떄문에 value가 전달이 되고,
object data type은 메모리에 reference가 저장되어진다.

object를 함수의 parameter로 전달하면, (passed by reference)

함수 안에서 object의 값을 변경했을 때 그대로 메모리에 적용이 되기 때문에 추후 변경사항이 메모리에 저장된다.

3. default parameters (ES6)

function test(a, b = 'yuna') {}

4. rest parameters (ES6)

function test(...args) {}

5. for loop 간단히 줄이기

5-1. of

	for (const arg of args) {}

5-2. .forEach(() => {});

	args.forEach((arg) => {});
    
  1. 자바스크립트에서 함수는 object이기 때문에
    함수이름을 콘솔에 입력하고 .를 쓰면 함수의 속성값을 확인해볼 수 있다.

  1. local scope
    밖에서는 안을 볼 수 없고, 안에서는 밖을 볼 수 있다.

  2. 모든 함수에는 return이 있고,
    없는 경우에는 return undefined가 생략되어 있다.

  3. early return, early exit
    함수 안에서 if & else를 번갈아쓰는 것보다는
    조건이 맞지 않을 때 빨리 return을 시키는 것이 낫다.

  1. function expression

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/function

*first-class function
functions are treated like any other variable
can be assigned as a value to variable
can be passed as an argument to other functions
can be returned by another function

first-class function을 가능하게 한 것이 function expression이다!
*function expression
a function declarartion can be called earlier than it is defined (hoisted)
a function expression is created when the execution reaches it

function declaration: hoisting이 가능하다. 즉 함수 선언 전에 위에서 함수를 미리 쓸 수 있다. (끌어올림)

일반적 함수: named function
function test() {};

function expression: anonymous function을 이용한 것, 정의하자마자 실행되므로 끌어올려지지 않는다. 즉 function expression을 정의하기 전에 해당 함수를 위에서 쓸 수 없다.

이름이 없는 함수: anonymous function
let functionExpression1 = function() {};
let functionExpression2 = () => {};

  1. callback function using function expressions

printYes(); => error! can't use function that was made with function expressions before function declaration (no hoisting for function expressions)

const printYes() = function() { //function expressions with anonyous function

console.log("yes");

}

const printNo() = function() { //function expression with anonymous function

cnosole.log("no");

}

function test(answer, printYes, printNo) {

if (answer && answer === 'yes') { //used && to check null instead of if

	printYes();
} else {
	printNo();
}

}

test(promt('love me?'), printYes, printNo);

  1. using named function in function expressions
    better debugging in debugger's stack traces
    recursions

function expressions에서 이름 있는 함수를 쓰는 경우는 매우 드물다!

디버깅할 때나, 함수 안에서 스스로 자신의 함수를 호출할 때 쓰인다.(recursion)
recursion은 call stack size excedeed error를 유발하므로 피보나치를 계산하는 등 특별한 경우가 아니면 쓰이지 않는다.

  1. arrow function
    여러줄인 경우, 블록 {} 안에 넣어야 하고 return을 꼭 해줘야 한다.

  2. IIFE (Immediately invoted function expression)
    함수를 선언함과 동시에 호출하는 방법!
    함수를 괄호()로 묶어주고 뒤에 ();를 하나 더 붙여준다.
    최근에 잘 쓰이진 않지만 JS에서 바로 함수를 호출하고 싶을 때 쓸 수 있다.

(function a() {})();

0개의 댓글