//Function
// fundamental building block in the program
// subprogram can be used multiple times
// performs a task or calculates a value
// 1. Function declaration
//function name(parm1, param2) { body... return;}
// one function === one thing
// naming : doSomething, command, verb
// e.g. createAndPoint -> createCard, createPoint
//function is object in JS
function printHello(){
console.log('Hello');
}
printHello();
function log(message){
console.log(message);
}
log('Hello');
log(1234); //일반적으로 string으로 처리됨!!
//TypeScript에서는 보다 명확한 매개변수의 형과 반환형 타입을 명시해야함!
//2. Parameters
//promises parameters : passed by value
//object parameters : passed by reference
function changeName(obj) {
obj.name = 'coder';
}
const ellie = {name : 'ellie'};
changeName(ellie);
console.log(ellie);
//3.Default parameters (added in ES6)
function showMessage(message, from) {
console.log(`${message} by ${from}`);
}
showMessage('Hi!'); //Hi! by undefined
function showMessages(message, from = 'unknown') {
console.log(`${message} by ${from}`);
}
showMessages('Hi!'); //Hi! by unknown
//4. Rest Parameters (added in ES6)
function printAll(...args) {
for(let i = 0; i<args.length; i++){
console.log(args[i]);
}
}
printAll('dream','coding','ellie'); //계속 받을수 있다.(배열 형태라서)
printAll('dream','coding','ellie','jihyeon'); //계속 받을수 있다.(배열 형태라서)]
function printAlls(...args) {
for(const arg of args){
console.log(args);
}
}
printAlls('dream','coding','ellie'); //계속 받을수 있다.(배열 형태라서)
function printAlls(...args) {
for(const arg of args){
console.log(args);
}
}
function printAlls2(...args){
args.forEach((arg) => console.log(arg));
}
printAlls2('dream','coding','ellie'); //계속 받을수 있다.(배열 형태라서)
//5. Local Scope
//밖에서는 안이 보이지 않고, 안에서는 밖을 볼 수 있다.
let globalMesage = 'global';
function printMessage() {
let message = 'hello';
console.log(message);
console.log(globalMesage);
}
printMessage();
//6. Return a value
function sum(a,b) {
return a +b;
}
console.log(`sum: ${sum(1,2)}`);
//Early return, early exit
//bad
function upgradeUser(user){
if(user.point > 10) {
//long upgrade logic...
}
}
//good
// funtion upgradeUsers(user){
// if(user.point <= 10) {
// return;
// }
// //long upgrade logic...
// }
//First-class function
//functions are treated like any other variable
// can be assigned as a value to variable.
// can be passed as argument to other functions.
// can be returned by another function.
//1. Function expression
// a function declaration can be called earlier than it is defined.
// a funtion expression is created when the execution reacheds it.
const print = function() { //anonymous function
console.log('print');
}
print(); //print
const printAgain = print;
printAgain(); //print
const sumAgain = sum;
console.log(sumAgain(1,3));//4
// 2. Callback function using function expression
function randomQuiz(answer, printYes, printNo) {
if(answer === 'love you'){
printYes();
} else {
printNo();
}
}
/** nmaed function
* better debugging in debugger's stack traces
* recursions
*/
const printYes = function() {
console.log('yes');
};
const printNo = function print() {
console.log('No');
//print(); 자기 자신 부르는 recursion도 있다.
};
randomQuiz('wrong',printYes, printNo); //no
randomQuiz('love you',printYes, printNo); //yes
//Arrow Function
//always anonymous
const simplePrint = function() {
console.log('simplePrint');
};
const simplePrints = () =>console.log('simplePrint!');
const add = (a,b) => a + b;
const simpleMultiply = (a,b) => {
//do something more
return a*b;
};
//IIFE : Immediately Invoked Function Expresion
(function hello(){
console.log('IIFE');
})();//바로 호출 가능함!
//Fun QUIZ TIME
//functional calculate(command, a, b)
//command : add, substract, divide, multiply, remainder
function calculate(command, a, b){
switch(command){
case 'add':
return a+b;
break;
case 'sustract':
return a-b;
break;
case 'divide':
return a/b;
break;
case 'multiply':
return a*b;
break;
case 'remainder':
return a%b;
break;
}
}
console.log(calculate('add',3,2));
console.log(calculate('substract',3,2));
console.log(calculate('multiply',3,2));
console.log(calculate('divide',3,2));
console.log(calculate('remainder',3,2));
출처 : 드림코딩 by 엘리
반응형
'Develope_Web_Programming > 01_HTML&CSS&JS' 카테고리의 다른 글
7.오브젝트 넌 뭐니?? (0) | 2021.02.14 |
---|---|
6. 클래스와 오브젝트의 차이 (0) | 2021.02.13 |
4. 코딩의 기본 operator, if, for loop (0) | 2021.02.13 |
3. 데이터 타입, data types, let vs var, hoisting (0) | 2021.02.13 |
2. 콘솔에 출력, Script async와 defer의 차이점 (0) | 2021.02.13 |
Uploaded by Notion2Tistory v1.1.0