반응형
드림코딩 엘리 - 자바스크립트 강의 #4
- Function
- fundamental building block in the program
- subprogram can be use multiple times
- performs a task or calculates a value
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
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); // => coder
3. Default parameters (added in ES6)
function showMessage(message, from) {
console.log(`${message} by ${from}`);
}
showMessage('Hi!'); //Hi! by undefined
function showMessage(message, from = 'unknown') {
console.log(`${message} by ${from}`);
}
showMessage('Hi!'); //Hi! by unknown
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');
5. Local scope
let globalMessage = 'global'; // global variable
function printMessage() {
let message = '';
console.log(message); // local variable
console.log(globalMessage); // OK
function printAnother() {
console.log(message); // OK
let childMessage = 'hello';
}
console.log(childMessage); // error
}
printMessage();
console.log(message); // error
밖에서는 안이 보이지 않고 안에서만 밖을 볼 수 있다.
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
// 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
- 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 (<-> named function)
console.log('print');
}
print();
const printAgain = print;
printAgain();
const sumAgain = sum;
console.log(sumAgain(1, 3));
2. Callback function using function expression
function randomQuiz(answer, printYes, printNo) {
if (answer === 'love you') {
printYes();
} else {
printNo();
}
}
// anonymous function
const printYes = function () {
console.log('yes!');
};
// named function
// better debugging in debugger's stack trace
// recursions
const printNo = function print() {
console.log('no!');
print(); // recursion (error, 이렇게 쓰진 않음)
};
randomQuiz('wrong', printYes, printNo); // no!
randomQuiz('love you', printYes, printNo); // yes!
// 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 Function Expression
(function hello() {
console.log('IIFE');
})();
- printYes, printNo : callback function
반응형
'프로그래밍 > JavaScript' 카테고리의 다른 글
[JS] 이벤트 위임을 활용한 Event Listener 중복 문제 해결 (0) | 2022.03.12 |
---|---|
[JS] 단축 평가(Short-Circuit Evaluation) 쉽게 이해하기 | &&, ||, 연산자 우선순위 (0) | 2022.03.07 |
[자바스크립트] class vs object, 객체지향 언어 클래스 정리 (0) | 2021.03.22 |
[자바스크립트] operator, if, for loop, 코드리뷰 팁 (0) | 2021.03.21 |
[자바스크립트] Data types, let vs var, hoisting (0) | 2021.03.21 |