티스토리 뷰
Function
- fundamental building block in the program
- subprogram can be used 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
function printHello() {
console.log('Hello');
}
printHello(); // Hello
function log(message) {
console.log(message);
}
log('Hello@'); // Hello@
log(1234); // 1234
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 = '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++) { // 1
console.log(args[i])
}
for (const arg of args) { // 2
console.log(arg);
}
args.forEach((arg) => console.log(arg)); // 3
}
printAll('dream', 'coding', 'ellie'); // deram, 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(); // hello, global
// 안에서는 밖을 볼 수 있지만, 안에서는 밖을 볼 수 없다.
6. Return a value
function sum(a, b) {
return a + b;
}
const result = sum(1, 2); //3
console.log(`sum: ${sum(1, 2)}`); // sum : 3
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 its 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));
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 debuggers's stack traces
// recursion
const printNo = function print() {
console.log('no!');
};
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 Expresion
(function hello() {
console.log('IIFE');
})();
※출처
'JavaScript & TypeScript' 카테고리의 다른 글
6. what is object (0) | 2020.11.14 |
---|---|
5. class vs object (0) | 2020.11.14 |
3. operator, if, for loop (0) | 2020.11.13 |
2. data types, let vs var, hoisting (0) | 2020.11.13 |
1. script async vs defer (0) | 2020.11.13 |
링크
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- dreamcoding
- js array
- ㅇㄷㅇㅈ
- 이펙티브자바
- 이펙티브자바 아이템60
- 프로그래머스
- JS 딥다이브
- 프로그래머스 SQL
- 김영한 http
- REST API
- http
- 이펙티브자바 아이템59
- js promise
- 백준
- java
- JPA 연관관계 매핑
- 모던자바스크립트
- 가상 면접 사례로 배우는 대규모 시스템 설계 기초
- 이펙티브자바 스터디
- GCP
- Spring Security
- BOJ
- js api
- 백기선 스터디
- HTTP 완벽가이드
- HTTP 완벽 가이드
- 드림코딩
- 김영한 JPA
- 패스트캠퍼스 컴퓨터공학 완주반
- 킹수빈닷컴
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
글 보관함