동캄의 코딩도장

JS [function] 본문

front/HTML&CSS&JS

JS [function]

동 캄 2022. 1. 23. 23:16

function

1. function 정의
   function name (param1, param2){body....return;}
   one function === one thing (중요)
   naming: doSomething, command, verb
   function is object in JS

2. parameters
   Premitive ---- call by value
   object  ---- call by reference

3. Default parameters
   ex) function showMessage(message, from = 'unknown'){
console.log(`${message} by ${from}`);
}
showMessage(`Hi!`);

--> from 값이 전달 받지 못하면 default값을 전달

4. Rest parameters
ex) function printAll(...args){
for (const arg of args){
console.log(arg);
});
... 으로 전달---> 배열(Object)로 전달

5. Local scope
함수 안에서 선언 --> 지역변수

6. return a value

return 값 없음 --> undefined를 return 함

7. Early return, Early exit

//bad

function upgradeuser(user){
    if (user.point >10){
        //long upgrad logic....
}

function upgradeUser(user){
   if (user.point <=10){
    return;
}

function Expression

First-class function
- 함수는 변수로 취급가능
- 변수로 할당가능
- 변수로 전달
- 리턴값으로 전달 가능
- hoisting 가능

I) function expression

ex)

const print = function(){
console.log('print');
}
print();
const printAgain = print;
printAgain();
const sumAgain = sum;
console.log(sumAgain(1,3));


II) Call back 
- 함수를 전달하고 나중에 다시 코드에의해 실행되는 것 (다시 불려져 오는것)
ex)

function randomQuiz(answer, printYes, printNo){
   if(answer==='love you'){
printYes();
}
else{
printNo();
}
}

Arrow function

// not arrow
const simplePrint = function () {
  console.log('simplePrint');
};

// arrow
const simpleprint = () => console.log('simplePrint!');
const add = (a,b) =>a+b;

IIFE : Immediately Invoked Function Expression

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

--> 바로 호출 됨

'front > HTML&CSS&JS' 카테고리의 다른 글

JS [Object]  (0) 2022.01.24
JS [Class]  (0) 2022.01.24
JS [operators]  (0) 2022.01.23
JS [variable]  (0) 2022.01.23
html [emmet]  (0) 2022.01.22