-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction.js
179 lines (110 loc) · 2.32 KB
/
function.js
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
function printHello(){
console.log('Hello');
}
printHello();
function log(message){
console.log(message);
}
log('Hellow@');
log(1234);
// 타입스크립트
// function log(meesage:string):number{
// console.log(message);
// return 0;
// }
// 2.Parameters
function changeName(obj){
obj.name='coder';
}
const ellie={name:'ellie'};
changeName(ellie);
console.log(ellie);
// 3.Default parameters
function showMessage(message,from){
console.log(`${message} by ${from}`);
}
showMessage('Hi!');
// 4.Rest parameter
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';
function printMessage(){
let message='hello';
console.log(message);
console.log(globalMessage);
function printAnother(){
console.log(message);
let childMessage='Hello';
console.log(childMessage);
}
}
printMessage();
// 6.Return a value
function sum(a,b){
return a+b;
}
const result=sum(1,2);
console.log(`sum: ${sum(1,2)}`);
// 7.Early return, early exit
// bad
function upgradeUser(user){
if(user.point>10){
}
}
// good
function upgradeUser(user){
if(user.point<=10){
return;
}
}
// 8.function expression
const print=function(){
console.log('print');
};
print();
const printAgain=print;
printAgain();
const sumAgain=sum;
console.log(sumAgain(1,3));
// sum 함수에 선언이 호출되기전에 선언이 된다.
// 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
const printNo=function print(){
console.log('no!');
// print();
}
randomQuiz('wrong',printYes,printNo);
randomQuiz('love you',printYes,printNo);
// Arrow function
// const simplePrint=function(){
// console.log('simplePrint!');
// };
const simplePrint=()=>console.log('simplePrint!');
const add=(a,b)=>a+b;
const simpleMultiply=(a,b)=>{
return a*b;
}
// IIFE
(function hello(){
console.log('IIFE');
})();