Function declaration
기능 : 하나의 함수는 한가지 일만 하도록
명명 : 함수명은 동사 command, verb 형태로
javascript에서 function은 object 타입
선언
function 함수명(매개변수){
실행문
}
매개변수의 경우
primitive 타입의 경우 passed by value (값 자체가 전달)
object 타입인 경우 passed by reference(참조 주소값 전달)
default parameter(ES6) 매개변수='default값'
Restparameter ...args : 배열로 값을 받는다
return 설정, 안할시 undefined
function expression
: a function declaration can be called earlier than it is defined.(hoisted)
: a function expression is created when the execution reaches it.
1. anonymous function, named function으로 함수를 변수로 선언하여 변수가 함수를 가리키도록 할당할 수 있다.
- named function으로 사용할 경우 : 나중에 debugging할 때 함수명을 알기 위해, recursion을 할 때 사용
- anonymous function -> arrow function 이용
2. arrow function(always anonymous function)
function 생략 매개변수=> 실행문이 한줄이면 {}생략, 한줄이상일 경우 {}블록 지정
3. 선언함과 동시에 호출하고 싶을 경우
(function 정의{})(); 로 호출 함수정의를 괄호로 묶고 마지막에 ()빈괄호 써주면 선언과 동시에 호출할 수 있다.
console.log('0. 함수 시작!!! function 기본')
function log(message){
console.log(message);
}
// 매개변수
log("Hello");
// default 매개변수
function showMessage(message,from='unknown'){
console.log(`${message} by ${from}`);
}
showMessage('Hi');
// rest parameters : 배열 형태로
// 배열 for, for of
function printAll(...args){
for (let index = 0; index < args.length; index++) {
console.log(args[index]);
}
for (const arg of args) {
console.log(arg);
}
}
printAll('dream','coding','fighting');
// return 설정, 안할시 undefined
function add(num1, num2){
return num1+num2;
}
console.log(add(1,2));
console.log("1. function expression 시작!!!");
const print=function(){
console.log('print');
};
print();
const printAgain=print;
printAgain();
const sumAgain=add;
console.log(sumAgain(1,3));
console.log("2. Callback function using function expression");
const printYes=function(){
console.log('Yes');
}
const printNo=function(){
console,log('No');
}
function randomQuiz(answer,printYes,printNo){
if(answer==='love you'){
printYes();
}else{
printNo();
}
}
randomQuiz('love you',printYes,printNo);
randomQuiz('ayo',printYes,printNo);
console.log('Arrow function(always anonymous)');
const simplePrint= () => console.log('simplePrint');
const sum=(a,b)=>a+b;
console.log('Quiz');
const calculate=function(command,a,b){
let result;
if(command==='add'){
console.log(`${command} 실행`);
result=a+b;
}else if(command==='substract'){
console.log(`${command} 실행`);
result=a-b;
}else if(command==='divide'){
console.log(`${command} 실행`);
result=a/b;
}else if(command==='multiply'){
console.log(`${command} 실행`);
result=a*b;
}else if(command==='remainder'){
console.log(`${command} 실행`);
result=a%b;
}
return result;
}
console.log(calculate('add',1,2));
console.log(calculate('substract',1,2));
console.log(calculate('divide',1,2));
console.log(calculate('multiply',1,2));
console.log(calculate('remainder',1,2));