JS 강의 필기 + 추가
function
a fundamental building block in the program
subprogram can be used multiple times
performs a task or calculates a value
function declaration
function name( params ) { body... return; }
prefer to make one function does one thing
naming: doSth (command/verb-like)
function is object in JS
// function without params. body에서 return undefined; 가 생략된 것
function printHello() {
console.log('Hello');
}
printHello();
// function with a param
function log(message) {
console.log(message);
}
log('hello');
parameters
primitive params: passed by value
object params: passed by reference
function changeName(obj) {
obj.name = 'phin';
}
const myName = { name: 'joe' };
console.log(myName); // joe
changeName(myName); // myName.name id is changed to 'phin'
console.log(myName); // phin
default params
added in ES6
function showMessage(message, from = 'someone') {
console.log(`${message} by ${from}`);
} // result: Hi! by someone
// 'someone'이라는 default param없이 from param을 안 줄 경우 result: Hi! by undefined
rest params ( ... )
params를 array로 받아서 넣음. 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('a', 'b', 'c');
early return, early exit
block 안에 많이 쓰면 가독성이 떨어지니 조건이 맞을 때만 필요한 로직을 실행하도록 작성
// 나쁜 예
function upgradeUser(user) {
if (user.point > 10) { /* long logic */}
}
// 좋은 예
function upgradeUser(user) {
if (user.point <= 10) {
return;
}
// long logic
}
first-class function
functions are treated like any other variable
can be assigned as a value to a variable
can be passed as an argument to other functions
can be returned by another function
function expression
hoisting 불가. a function expression is created when the execution reaches it.
cf. a function declaration can be called earlier than it is defined. (hoisted)
print(); // Uncaught ReferenceError: Cannot access 'print' before initialization
const print = function () {
console.log('print');
};
print(); // print 출력
const printAgain = print;
printAgain(); // print 출력
callback function using a function expression
function randomQuiz(answer, printYes, printNo) {
// 이때 printYes와 printNo가 callback function
if (answer === 'love you') {
printYes();
} else {
printNo();
}
}
const printYes = function () { // anonymous function
console.log('yes');
}
const printNo = function print() {
// named function. intend to show the function name in debugger's stack traces
console.log('no');
// print(); // recursions
}
randomQuiz('wrong', printYes, printNo);
randomQuiz('love you', printYes, printNo);
arrow function
always anonymous. block을 사용하는 arrow function을 쓰면 return을 꼭 써야됨.
const simplePrint = () => console.log('print');
const add = (a, b) => a + b;
const substract = (a, b) => {
// do sth
return a - b;
}
IIFE: Immediately Invoked Function Expression
( 함수선언 )();
호출 즉시 실행
( function hello() {
console.log('IIFE');
} )();
'JS' 카테고리의 다른 글
JS - array (0) | 2020.12.24 |
---|---|
JS - object (0) | 2020.12.23 |
JS - class (0) | 2020.12.22 |
JS - operator (0) | 2020.12.21 |
JS - variable (0) | 2020.12.19 |