rhanziy

javascript. 함수 function 본문

Html_css_js

javascript. 함수 function

rhanziy 2022. 1. 18. 02:23
function changeName(obj) {
    obj.name = 'coder';
}

const rhanyi = { name: 'rhanyi' };
changeName(rhanyi);
console.log(rhanyi);

function showMessage(message, from = 'unknown') {
    console.log(`${message} by ${from}`);
}
showMessage('hi');

function printAll(...args) {  
    // 아래 세개는 같은 결과값.
    for (let i = 0; i < args.length; i++){
        console.log(args[i]);
    }

    for(const arg of args) {
        console.log(arg);
    }

    args.forEach((arg) => console.log(arg));
}
printAll('dream', 'coding', 'rhanyi');

function upgradeUser(user) {
    if (user.point > 10) {
        // ...logic
    }
}  // -> bad
function upgradeUser(user){
    if (user.point <= 10) {
        return;
    }
    // ...logic
}  // -> early return, early exit good

const print = function( ) { // 익명함수
    console.log('print');
}
print( );
const printAgain = print;
printAgain( );
// 함수도 호이스팅이 된다.

//------------------콜백함수 기본-------------------//
// 함수의 파라미터로 함수를 받는다.
function randomQuiz(answer, printYes, printNo) {
    if ( answer === 'love you' ) {
        printYes( );
    } else { printNo( ); }
}

const printYes = function( ){
    console.log('yes!');
}
const printNo = function print( ){
    console.log('no!');
}
randomQuiz('wrong', printYes, printNo);
randomQuiz('love you', printYes, printNo);

// Arrow function
// const simplePrint = function( ) {
//     console.log('simplePrint');
// }
const simplePrint = ( ) => console.log('simplePrint');
const add = (a, b) => a + b ;

// IIFE : Immediately Invoked Function Expression 선언함과 동시에 함수호출
(function hello( ) {
    console.log('IIFE');
})( );

//Quiz
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));
Comments