Js_함수 (2)

춤추는 병따개·2023년 2월 1일
0
post-thumbnail

함수(1)에 이어서 함수 설명 추가

Data type : Function
Statement : Function

출처: SCALER Topic

1️⃣ Funtion declaration

  • function name(param1, param2) { body... return;}
    *parameter = 매개변수
  • one function === one thing
  • naming : doSomething, command, verb 함수는 동작하는 것이기 때문에 동사로 지어야함
  • e.g. createCardAndPiont -> createCard, createPoint
  • function is object in JS
// 키워드   함수 이름  파라미터는 없음(매개변수)
function printHello() {
    console.log('Hello');
}  //콘솔에 Hello를 출력해
printHello();
//함수 호출
    //함수 이름  파라미터 (매개변수) message 
function log(message) {
    console.log(message);
}
log('Hello!');
log(123);
//로그 함수 호출

2️⃣ Parameters (매개 변수)

  • 원시 타입은 메모리에 '값'이 저장. 오브젝트 타입은 메모리에 '레퍼런스'가 저장!
  • premitive parameters : padded by value | 원시타입 매개변수는 메모리의 값이 그대로 전달
  • object parameters : passed by reference | 객체타입 매개변수는 레퍼런스가 전달!
function changeName(obj) {
    obj.name = 'coder';
}
const ellie = { name: 'ellie' };    //ellie의 이름을 code로 변경하는 식
changeName (ellie);
console.log(ellie)
//{name : 'coder'}

<해설>
const ellie는 { name : 'ellie' } 이다.
changeName 함수의 (매개변수로 ellie)를 넣으면
obj.name = 'coder'; 에 의해 ellie.name = 'coder';라는 식이 되어
ellie 는 { name : 'coder' }가 된다!

3️⃣ Default Parameters

//                  매개변수가 두 개  원하는 디폴트값 지정 가능!
function showMessage(message, from = 'unknown') {
    console.log(`${message} by ${from}`);
}
showMessage(`Hi!`);

4️⃣ Rest parameters (added in ES6)

function printAll(...args){ //...args -> array 배열
    for ( let i = 0; i < arguments.length; i++) {     //방법 1
        console.log(args[i]);
    }

    for (const arg of args) {                          //방법2
        console.log(arg);                              
    }

    args.forEach((arg) => console.log(arg));           //방법3
}
printAll('dream', 'coding', 'ellie')

5️⃣ Lcoal scope

영향을 주는 방향 : Global -> local (가능) local -> Global (불가능)

let globalMessage = 'global'; // global variable
function printMessage() {
    let message = 'hello';
    console.log(message); // local variable
    console.log(globalMessage)   //global  상위 블럭의 정보는 하위 블럭에서도 적용 됨!
    function printAnother() {
        console.log(message);
        let childMessage = 'bye';
    }
    //console.log(childMessage)     // error 하위 블럭 정보는 상위 블럭에서 적용 안됨!
}
printMessage();

6️⃣ Return a value

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

7️⃣ Early returnm early exit

< 조건 > 10보다 크다!
식 작성의 안좋은 예

function urgradeUser(user) {
    if (user.point > 10) {          //조건에 충족할때
        //long upgrade logic...    // 블럭 안에 나머지 로직 작성
    }                              //가독성 떨어짐.
}
function upgradeUser(user) {
    if (user.point <= 10) {        // 조건에 부합하지 않을때
        return;                    //함수 종료
    }
    // long upgrade logic...       // 조건이 맞을때만 필요한 로직 실행
}

First-class function

functions are treated like any other variable 함수는 다른 변수와 마찬가지로
an 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 defiend. (hoisted)
  • a function expression is created when the execution reaches it.
const print = function () {         //이름 없는 함수 anonymous function
//const pritn = function name ()    // 이름 있는 함수 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();
    }
}
// anonymous function
const printYes = function () {
    console.log('yes!');
};
// named function
// better debugging in debrgger's stack traces
// recurisions
const printNo = function print() {
    console.log('no!');
};
randomQuiz('wrong', printYes, printNo);
randomQuiz('love you', printYes, printNo);

Arrow function

always anonymous

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

// const add = function () {
//     return a + b;
// };
const add = (a, b) => a + b; 

//복잡한 식의 경우는 아래 처럼
const simpleMultiply = (a, b) => {
    //do sometying more
    return a * b;
};

IIFE

Immediately Invoeked Function Ecpression
함수의 선언을 (괄호)로 묶고 ();호출하면!! 함수를 바로 볼 수 있다!

(function hello() {
    console.log('IIFE');
}) ();
//IIFE
출처:드림코딩
profile
FE 개발 공부 중

0개의 댓글