0. Function
function name (param1, param2) { body . . . return;}
one function === one thing
naming : doSomething, command, verb
function is object in JS!!! → ~prototype~
+ TypeScript Playground
function log(message : string) : number {
console.log(message);
return;
}
1. Parameters
function changeName(obj){
obj.name = 'cucu';
}
const bob = { name: "bob"};
changeName(bob);
console.log(bob);
2. Default Parameters
function showMessage(message, from = `idon'tknow`){
console.log(`${message} by ${from}`);
}
showMessage('goooood');
3. Rest Parameters
. . . 배열 형태로 전달
function printAll(...args){
for (const arg of args){
console.log(arg);
}
}
printAll('a','b','c');
4. Local scope
"밖에서는 안이 보이지 않고, 안에서만 밖을 볼 수 있다."
5. Return
return undefined;
6. Early return
return : 함수 실행 종료, 주어진 값을 함수 호출 지점으로 반환.
조건이 맞지 않을 때는 함수를 빨리 종료 : return;
7. Function expression
Function delaration → hoisted O
const print = function(){ //anonumous function, function print() : named function
console.log('print');
};
print();
const printAgain = print;
printAgain();
8. Callback function
함수가 파라미터로 전달
function randomQuiz(answer, printYes, printNo){
if (answer === "cucubob"){
printYes();
} else {printNo();}
}
function printYes(){
console.log("yes!!");
}
function printNo(){
console.log("no!!");
}
randomQuiz("cocobab", printYes, printNo);
const printNo = function print() // debugging 에 함수 이름 나오게 하기 위해서.
print(); // 스스로 호출 가능
9. Arrow function
const simplePrint = () => console.log("simpleprint!");
simplePrint();
10. IIFE
(function hello(){
console.log("iife");
})();
IIFE 를 잘 쓸지 의문,,
+Quiz
// function calculate(command, a, b)
// command : {add, substract, divide, multiply, remainder}
let a = 0;
let b = 0;
function calculate(command, a, b){
if (command === 'add'){
console.log(a + b);
} else if (command === 'substract'){
console.log(a - b);
} else if (command === 'divide'){
console.log(a / b);
} else if (command === 'multiply'){
console.log(a * b);
} else if (command === 'remainder'){
console.log(a % b);
}
}
calculate('add', 1, 6);
calculate('substract', 1, 6);
calculate('divide', 6, 3);
calculate('multiply', 100, 60);
calculate('remainder', 53, 6);
흠 실습할 때는 쉬웠는데, 갑자기 혼자 하려니 막막했다. 그래도 혼자 해결했기에 조금의 뿌듯함..
앞으로 많은 노력을 해야겠구나..