본문 바로가기
Develope_Web_Programming/01_HTML&CSS&JS

5. Arrow Function은 무엇인가?

by 스타트업_디벨로퍼 2021. 2. 13.
💡
function은 원하는 기능에 맞춰서 만든 함수!! function → sub-program!! input → output!! API(Application Programming Interface)에 대부부분의 기능이 다 적혀 있다!!
//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));
 

Notion2Tistory

 

boltlessengineer.github.io

출처 : 드림코딩 by 엘리 

youtu.be/e_lU39U-5bQ

 

반응형