Function
- fundamental building block in the program
- performs a task or calculates a value
- JavaScript에서 Function은 Sub-program이라고도 한다.
- 대체적으로 parameters를 받아서(input/x) return을(output/f(x)) 한다.
- 함수의 이름을 보고 대체적인 기능을 알 수 있다. (알 수 있게 짜야한다.)
1. Function declaration
- function name(para1, param2) { body... return; }
- one function === one thing 하나의 함수는 한가지만 하도록.
e.g. createCardAndPoint 이런식으로 이름이 붙여진다면 -> createCard, createPoint 로
- naming: doSomething, command, verb 동사형으로
- function is object in JS => 변수나 파라미터, 함수로 리턴될수도 있다.
function printHello() {
console.log('Hello');
}
printHello();
//위보다는 아래처럼.
function log(message) {
console.log(message);
}
log('Hello@'); //Hello@
log(1234); //1234
*JavaScript 와 TypeScript
JS에서는 type을 정해주지 않지만 TypeScript에서는 parameter type과 return type을 정해준다.
//in TS
function log(message: string): number {
console.log(message);
return 0;
}
//string은 parameter type. number는 return type
//in JS
function logInJS(message) {
console.log(message);
return 0;
}
parameter name,type, return type으로 무슨함수인지 추측가능.
=> 협업 or api를 제공할 때 조금 더 명확하고 쉽게 만들어준다.
2. Parameters
- primitive parameters: passed by value (memory에 value가 저장되기 때문에 value전달)
- object parameters: passed by reference (memory에 reference가 저장되기 때문에 reference전달)
function changeName(obj) {
obj.name = 'coder';
}
const ellie = { name: 'ellie' };
//object이기 때문에 value가 아니라 ellie가 가리키는 reference가 저장.
changeName(ellie);
//ellie 가리키고 있는 곳의 name을 coder로 변경.
console.log(ellie); //{name: "coder"}
3. Default parameters (added in ES6)
function showMessage(message, from = 'unknown') {
console.log(`${message} by ${from}`);
}
showMessage('Hi!'); //Hi! by unknown
//message는 전달됐지만 from은 전달되지 않음. from은 undefined가 된다.
예전에는 undefined일 경우를 대비해 if문으로 default값을 설정했지만 ES6부터는 from ='unknown'으로 간단하게 가능
4. Rest parameters (added in ES6)
... 을 사용하면 배열 형태로 전달
function printAll(...args) { //...args가 배열형태로 전달.
for (let i = 0; i < args.length; i++) {
console.log(args[i]);
}
for (const arg of args) { //위에 for문을 이렇게 간단하게도 쓸 수 있다.
console.log(arg);
}
args.forEach((arg) => console.log(arg)); //더 간단하게 foreach와 Arrow로
}
printAll('dream', 'coding', 'ellie');
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();
밖에서는 안이 보이지 않고 안에서만 밖을 볼 수 있다!!
6. Return a value
function sum(a, b) {
return a + b;
}
const result = sum(1, 2); // 3
console.log(`sum: ${sum(1, 2)}`);
//return type이 없는 함수들은 return undefined가 생략되어 있는것과 같다. 생략가능.
7. Early return, early exit
현업에서 쓰이는 tip!
// *bad
function upgradeUser(user) {
if (user.point > 10) {
// long upgrade logic... 이렇게 block안에 logic을 많이 쓰면 가독성이 떨어진다.
}
}
// *good
function upgradeUser(user) {
if (user.point <= 10) {
return;
}
// long upgrade logic...
//이런식으로 조건이 맞지 않은것은 빨리 return 시키고 나머지에 logic을 길게 쓰는게 좋다.
}
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. (parameter로 전달가능)
- 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 () {// 이런식으로 함수를 선언함과 동시에 print라는 변수에 할당
// anonymous function : 함수에 이름이 없는 것
console.log('print');
};
print();
const printAgain = print; //다른변수에도 할당 가능
printAgain();
//일반적인 함수와 가장 다른점은 function declaration은 hoisting이 가능하다!!
// => 함수가 선언되기 이전에 호출가능. JS engine이 선언들을 가장 위로 올려주기때문(hoisting)
2. Callback function using function expression
function randomQuiz(answer, printYes, printNo) {
if (answer === 'love you') {
printYes();
} else {
printNo();
}
}
const printYes = function () {// anonymous function
console.log('yes!');
};
const printNo = function print() {// named function
console.log('no!');
};
randomQuiz('wrong', printYes, printNo);
randomQuiz('love you', printYes, printNo);
//named function is better debugging in debugger's stack traces
*recursions : 함수안에서 자기함수를 부르는 것
피보나치수를 계산하거나 반복해서 평균값을 계산할때 사용
* Arrow function
- 함수를 간결하게 만들어 준다
- 항상 이름이 없는 함수. always anonymous
const simplePrint = function () {
console.log('simplePrint!');
};
//위 함수를 arrow function으로 쓰면
const simplePrint = () => console.log('simplePrint!');
// * parameter 있을 때
const add = (a, b) => a + b;
// * 한 줄이 아니라 block이 필요할 때 : return값을 반드시 써야함
const simpleMultiply = (a, b) => {
// do something more
return a * b;
};
*IIFE: Immediately Invoked Function Expression (선언함과 동시에 호출)
(function hello() {
console.log('IIFE');
})();
//최근에 잘 쓰이지는 않지만 이런 방법도 있다.
* Quiz
Calculate 계산기만들기
- 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('unkown command');
}
}
console.log(calculate(add, 3, 5)); //8
'공부 > JavaScript' 카테고리의 다른 글
object (dreamcoding) | ES6 (0) | 2021.01.27 |
---|---|
class vs object, class정리 (dreamcoding) | ES6 (0) | 2021.01.27 |
operator, if, for loop ~(dreamcoding) | ES6 (0) | 2021.01.25 |
async, defer / data types ~ (dreamcoding) | ES5+ (0) | 2020.12.09 |
중복 제거하고 정렬하기(Set, sort) (0) | 2020.10.25 |