function 함수명(매개변수) {실행할 코드}
let 변수 = function(매개변수) {실행할 코드}
함수명()
(함수표현식으로 정의한 함수는 변수명===함수명)undefined
.(매개변수에 아무것도 전달되지 않았을 때)함수명(전달인자)
함수 호출 = invoke (a fancy word for run, or execute)
함수는 hoisting 되어서 함수를 함수 선언문 전에 호출할 수 있음
익명 함수 : 함수이름이 없는 함수. 주로 이벤트 핸들러와 사용됨.
function() { alert('hello'); }
- 익명함수 예시
function logKey(event) { console.log(`You pressed "${event.key}".`); } textBox.addEventListener('keydown', logKey); // 위에서 logKey() 함수를 사용하는 대신, event parameter 만 받아오는 익명함수를 addEventListener()로 보낼 수 있음. // --> textBox.addEventListener('keydown', function(event) { console.log(`You pressed "${event.key}".`);
화살표 함수 :
Syntax:
(param1, param2, …, paramN) => { statements } (param1, param2, …, paramN) => expression // 다음과 동일함: => { return expression; } // // 매개변수가 하나뿐인 경우 괄호는 선택사항: (singleParam) => { statements } singleParam => { statements } // 매개변수가 없는 함수는 괄호가 필요: () => { statements }
- 화살표 함수 예시
// -->익명함수 예시를 아래와 같이 화살표 함수로 변경 가능 textBox.addEventListener('keydown', event => console.log(`You pressed "${event.key}".`)); });
매개변수 = Function parameters.
Parameters are sometimes called arguments, properties, or even attributes.
Default parameters
If you're writing a function and want to support optional parameters, you can specify default values by adding =
after the name of the parameter, followed by the default value:
function hello(name = 'Chris') {
console.log(`Hello ${name}!`);
}
hello('Ari'); // Hello Ari!
hello(); // Hello Chris!