자바스크립트에 최근에 추가된 class는 java처럼 pure한 oop가 아니라 프로토 타입을 베이스로 한 가짜 oop이다. 따라서 자바스크립트도 procedural language 중의 하나이다.
procedural language에서는 함수가 프로그램에서 중요한 역할을 담당한다.
따라서 때로는 function을 program 안에서 각각의 작은 단위들을 수행하는 sub-program이라고 부르기도 한다.
하나의 함수는 한 가지의 일만 하도록 만들어야 한다.
함수의 이름 = doSomething, command, verb 같이 동사의 형태로 지정한다.
function is object in JS (변수 할당, 인수로 전달, 리턴값)
자바스크립트는 Type이 없으므로 데이터 타입을 예상하기 어렵다.
premitive data type은 메모리에 value가 그대로 저장돼 있기 떄문에 value가 전달이 되고,
object data type은 메모리에 reference가 저장되어진다.
function test(a, b = 'yuna') {}
function test(...args) {}
for (const arg of args) {}
args.forEach((arg) => {});
local scope
밖에서는 안을 볼 수 없고, 안에서는 밖을 볼 수 있다.
모든 함수에는 return이 있고,
없는 경우에는 return undefined가 생략되어 있다.
early return, early exit
함수 안에서 if & else를 번갈아쓰는 것보다는
조건이 맞지 않을 때 빨리 return을 시키는 것이 낫다.
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
일반적 함수: named function
function test() {};
이름이 없는 함수: anonymous function
let functionExpression1 = function() {};
let functionExpression2 = () => {};
console.log("yes");
}
cnosole.log("no");
}
function test(answer, printYes, printNo) {
printYes();
} else {
printNo();
}
}
test(promt('love me?'), printYes, printNo);
디버깅할 때나, 함수 안에서 스스로 자신의 함수를 호출할 때 쓰인다.(recursion)
recursion은 call stack size excedeed error를 유발하므로 피보나치를 계산하는 등 특별한 경우가 아니면 쓰이지 않는다.
arrow function
여러줄인 경우, 블록 {} 안에 넣어야 하고 return을 꼭 해줘야 한다.
IIFE (Immediately invoted function expression)
함수를 선언함과 동시에 호출하는 방법!
함수를 괄호()로 묶어주고 뒤에 ();를 하나 더 붙여준다.
최근에 잘 쓰이진 않지만 JS에서 바로 함수를 호출하고 싶을 때 쓸 수 있다.
(function a() {})();