JS/[드림코딩] 엘리 (완)

05강. Arrow function, 함수의 선언과 표현

web_seul 2020. 7. 1. 21:05
반응형

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(param1, param2) {body.. return;}

- one function === one thing

- naming: doSomething, command, verb

ex) createCardAndPoint -> createdcard, createPoint

- function is object in JS_ 변수할당가능, parameter전달, function return o

function printHello(){
    console.log('Hello');
}
printHello();		//Hello
function log(message){
    console.log(message);
}
log('Hello@');		//Hello@
log(1234);		//1234(string)

Typescript는 type설정필요_ 명확하고 간편한 코딩

//TypeScript

function log(message: string): number{
	console.log(message);
	return 0;
}


//JavaScript

"use strict";
function log(message){
	console.log(message);
    return 0;
}

 

2. Parameters

- premitive parameters: passed by value

- object parameters: passed by reference

function changeName(obj){
    obj.name = 'coder';
}

const ellie = {name: 'ellie'};
changeName(ellie);
console.log(ellie);	//{name: "coder"}

 

3. Default parameters (added in ES6)

function showMessage(message, from){
if(from === undefined){
	from = 'unknown;'
    }
    console.log(`${message} by ${from}`);
 }
 showMessage('Hi!');  

//간략히
function showMessage(message, from = 'unknown'){
    console.log(`${message} by ${from}`);
}
showMessage('Hi!');	//Hi! by unknown

 

4. Rest parameters (added in ES6)_ array style

function printAll(...args){
    for (let i =0; i<args.length; i++){		//way1
        console.log(args[i]);
	}
    for(const arg of args){			//way2
        console.log(arg);
    }
    args.forEach((arg) => console.log(arg));	//way3
}
printAll('dream','coding','ellie');	//dream, coding, ellie

 

5. Local scope_ tint처리된 유리창, 안에서는 밖에 보이지만 밖에서는 안이 보이지않는다

let globalMessage = 'global'; 	//global variable

function printMessage(){
    let message = 'hello';
    console.log(message); 	//local variable
    console.log(globalMessage);

    function printAnother(){
        console.log(message);
        let childMessage ='hello';
    }
    //console.log(childMessage);	//error
    //return undefined
}
printMessage();

//console.log(message);	//error

 

6. Return a value

function sum(a,b){
    return a+b;
}
const result = sum(1,2); 
console.log(`sum: ${sum(1,2)}`);	//sum: 3

 

7. Early return, early exit_가독성 향상

//bad
function upgradUser(user){
    if(user.point >10){
        //long upgrade logic...
    }
}


//good
function upgradeUser(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 an argument to other functions.

  can be returned by another function

 

1) Function expression

a function declaration can be called earlier than it is defined. (hoisted)

a function expression is created when the execution reaches it.

const print = function(){ //annoymous function(이름이 없는 함수)↔ named 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();
    }
}

//annoymous function
const.printYes = function (){
    console.log('yes!');
};

//named function
//better debugging in debugger's stack traces
//recursions
const.printNo = function print(){
    console.log('no!');
    //print();  //infinite route
};

randomQuiz('wrong', printYes, printNo);  	//no!
randomQuiz('love you', printYes, printNo);  	//yes!

 

Arrow function_ always anonymous

const simplePrint = function(){
    console.log('simplePrint!');
}

//간략히
const simplePrint = () => console.log('sinplePrint!');
const add = function(a,b){
    return a+b;
}

//간략히
const add = (a,b) => a+b;
const simpleMultiply = (a,b)=>{
	//do something more
	return a*b;
};

 

IIFE: Immediately Invoked Function Expression_함수 즉시호출

(function hello(){
    console.log('IIFE');
})();

 

Fun quiz time

function calculate(command, a,b)_ command: add, substract, divide, multiply, ramainder

function calculate(command, a,b){
    switch(command{
        case 'add':
            return a+b;
        case 'substract':
            return a-b;
        case 'divide':
            return a/b;
        case 'multiply':
            return a*b;
        case 'remainder':
            return a%b;
        default:
            throw Error('unknown command');
    })
}
console.log(calculate('add',2,3));
반응형