Function
[Function]
- 프로그램을 구성하는 기본적인 building block
- subprogram으로도 불리며, 재사용이 가능
- 한가지의 task, 계산을 위해 사용됨
- Function의 이름, Input, Output이 중요하다
[Function declaration]
- function name(param1, param2) { body... return; }
- 하나의 함수는 한가지의 일만 수행하도록 작성해야한다.
- 이름을 작성할때 doSomething, command, verb 와 같이 작성하기
- 함수는 object이기때문에 변수에 할당, 파라미터로 전달, 함수 리턴 가능
// 1. Function declaration
// function name(param1, param2) { body... return; }
// one function === one thing
// naming: doSomething, command, verb
// e.g. createCardAndPoint -> createCard, createPoint
// function is object in JS
function printHello() {
console.log('Hello');
}
printHello();
function log(message) {
console.log(message);
}
log('Hello@');
log(1234);
[Parameters]
// 2. Parameters
// primitive parameters: passed by value
// object parameters: passed by reference
function changeName(obj) {
obj.name = 'coder';
}
const ellie = { name: 'ellie' };
changeName(ellie);
console.log(ellie);
[Default parameters]
- 파라미터의 default값을 줘서 1개의 파라미터값만 주어져도 default값이 출력
// 3. Default parameters (added in ES6)
function showMessage(message, from = 'unknown') {
console.log(`${message} by ${from}`);
}
showMessage('Hi!');
[Rest parameters]
- 배열형태로 파라미터 전달
// 4. Rest parameters (added in ES6)
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', 'ellie');
[Local Scope]
- 이전에 block scope, global scope에 대해 배웠다.
- 밖에서는 안이 보이지 않고 안에서만 밖을 볼 수 있다.
/ 5. Local scope
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
}
printMessage();
[Return a value]
// 6. Return a value
function sum(a, b) {
return a + b;
}
const result = sum(1, 2); // 3
console.log(`sum: ${sum(1, 2)}`);
[Early return, early exit]
- 여러개의 if else로 나중에 return 하는거 보다는, 조건이 아닐 경우 return을 먼저 하도록! 그 후에 로직 작성
/ 7. Early return, early exit
// bad
function upgradeUser(user) {
if (user.point > 10) {
// long upgrade logic...
}
}
// good
function upgradeUser(user) {
if (user.point <= 10) {
return;
}
// long upgrade logic...
}
First-class Function
[Function expression]
- 할당되고, 파라미터로 전달되고, 리턴가능
- 함수의 이름 없는 경우 anonymous function, 이름이 있는 경우 named function
- fucntion declaration은 hoisting가능함 --> 함수 선언되기 이전에 호출해도 작동된다.
// 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 () {
// anonymous function
console.log('print');
};
print();
const printAgain = print;
printAgain();
const sumAgain = sum;
console.log(sumAgain(1, 3));
[Callback function using function expression]
- 함수를 전달해서 상황에따라 함수를 부르는 것을 callback function
// 2. Callback function using function expression
function randomQuiz(answer, printYes, printNo) {
if (answer === 'love you') {
printYes();
} else {
printNo();
}
}
[anonymous function]
// anonymous function
const printYes = function () {
console.log('yes!');
};
[named function]
// named function
// better debugging in debugger's stack traces
// recursions
const printNo = function print() {
console.log('no!');
};
randomQuiz('wrong', printYes, printNo);
randomQuiz('love you', printYes, printNo);
[Arrow function]
- 함수를 간결하게 만들어주는 것
- 이름이 없는 anonymous function
// Arrow function
// always anonymous
// const simplePrint = function () {
// console.log('simplePrint!');
// };
const simplePrint = () => console.log('simplePrint!');
const add = (a, b) => a + b;
const simpleMultiply = (a, b) => {
// do something more
return a * b;
};
[IIFE : Immediately Invoked Fundtion Expression]
- 함수를 선언함과 동시에 호출하는 방법
// IIFE: Immediately Invoked Function Expression
(function hello() {
console.log('IIFE');
})();
// Fun quiz time❤️
// function calculate(command, a, b)
// command: add, substract, divide, multiply, remainder
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)); //5
Thanks for 드림코딩
'Front-end > Web' 카테고리의 다른 글
[JS] 오브젝트 (0) | 2021.08.27 |
---|---|
[JS] 클래스와 오브젝트의 차이점, 객체지향 언어 클래스 정리 (0) | 2021.08.27 |
[JS] operator, if, for loop 코드리뷰 팁 (0) | 2021.08.27 |
[JS] data types, let vs var, hoisting (0) | 2021.08.26 |
[JS] 콘솔에 출력, script async와 defer의 차이점 및 공부방향 (0) | 2021.08.26 |
댓글