IT/JS

Function

프티 2021. 5. 20. 20:56
반응형

1. function

  • 함수는 object의 일종이다.
  • JS에서는 타입 정의를 따로 하지 않기 때문에 이것이 숫자인지 문자열인지 난해할 수 있다.
  • 따라서 TS(TypeScript)를 활용하여 정확하게 변수의 데이터타입을 지정해주어야한다.
  • TS활용 예시)
    function log(x: string): number {} // 함수에 타입을 정하는 방식
  • 일반적인 함수 선언
    function log(x){
        console.log(x);
    } ​

2. parameters

  • primitive parameters: passed by value
  • object parameters: passed by reference
    function changename(x){
        x.name='coder';
    }
    
    const hty = {name:'hty'}; // type of hty : object
    console.log(hty); // hty
    changename(hty);
    console.log(hty); // coder

3. default parameters

  • 함수에 입력해야할 변수가 없을 때, 자동으로 디폴트 값을 출력한다.
    function showmessage(message,from){
        console.log(`${message} by ${from}`);
    }
    
    showmessage('a!'); // a! by undefined

4. rest parameters

  • ES6에서 추가됨
  • ' ... '은 배열을 나타낸다.
    function printall(...args){
        for(let i=0; i<args.length;i++){
            console.log(args[i]);
        }
    }
    
    printall('a','b', 'c');​

5. local scope

  • {} 밖에서는 안을 볼 수 없지만, 안에서는 밖을 볼 수 있다.

6. return a value

  • 리턴 값을 지정하거나, undefined이거나(undefined의 경우 생략이 가능하다.)
 

7. early return, early exit

  • 박스안에서 긴 로직을 작성하면 가독성이 떨어짐 -> 효율 감소
    //bad
    function upgrade(x){
        if(x.point > 10) {
            //upgrade logic
        }
        else{
            return;
        }
    }
    //good
    function upgrade(x){
        if(x.point <= 10) {
            return;
        }
        //upgrade logic
    }​

first-class function

  1. 변수로 지정될 수 있다.
  2. 인자로 넘겨질 수 있다.
  3. 다른 함수에 의해 리턴될 수 있다.

 

1. function expression

  • 함수 자체는 hoisting이 가능하다.
  • anonymous function (함수의 이름이 없다.)
    const print = function () {
    	console.log('print');
    };​
  • named function
    디버거의 stack traces의 디버깅에 좋다.
    함수안에서 자신을 호출하면 recursions 발생 -> 프로그램이 다운될 수 있다.
    const print = function name() {
        console.log('print');
        name(); // 무한 반복으로 인한 오류 발생
    }​
  • print(); //변수를 함수 이름을 호출하듯이 사용 가능. --> 단 호이스팅을 불가능.
    
    const printagain = print; 
    printagain();//변수로 함수를 정의하고 다시 다른 변수로 표현할 수 있음.

2. callback function using function expression

  • 함수를 변수로 불러오기
    function randomquiz(answer, printyes, printno){
        if (answer==='love you'){
            printyes();
        }
        else{
            printno();
        }
    }
    
    //CALLBACK 함수 정의 후
    const printyes = function () {
        console.log('me too');
    };
    const printno = function () {
        console.log('what?');
    };
    
    randomquiz('s',printyes,printno); // what?
  • arrow function
    always anonymous
    const a = () => console.log('sss');
    const add1 = (a,b) => a+b;
    const multi = (a,b) => { // 한 줄 이상의 arrow function 작성 시
        //,,,
        return x;
    }
    
    //IIFE: Immediately Invoked Function Expression
    //괄호로 덥고 ();를 입력하면 바로 함수 호출이 가능하다.
    (function a(){
        console.log('a');
    })();​

공부한 내용을 토대로 원하는 계산 방식과 숫자 두 개를 입력하면 그에 맞게 연산을 수행하는 코드를 작성해보았다.

const add = (a,b) => a+b;
const substract = (a,b) => a-b;
const divide = (a,b) => a/b;
const multiply = (a,b) => a*b;
const remainder = (a,b) => a%b;

function calculate(command,a,b){
    console.log(`the answer is ${command(a,b)}`);
}

calculate(remainder,3,2); // the answer is 1

 

반응형

'IT > JS' 카테고리의 다른 글

null의 타입, trim()  (0) 2021.07.22
Array  (0) 2021.05.20
Class  (0) 2021.05.20
Operator, Control flow statement  (0) 2021.05.20
변수타입, 데이터타입, let vs var, hoisting (드림코딩 by 엘리)  (0) 2021.05.06