function name(param1, param2) { body... return;}
one function === one thing
naming: doSomething, command, verb
함수의 이름은 동작하는/ 동사형태도 지어야 한다.
e.g. createCardAndPoint -> createCard, createPoint
function is object in JS
functiton log(message) {
console.log(message);
return 0;
}
: 자바스크립트에서는 출력되는 값의 type을 알 수 없다. (이건 Number인지..)
[TypeScipt]
functiton log(message string): number {
console.log(message);
return 0;
}
:TypeScipt에서는 return 값을 nember로 출력한다는 것을 코드를 통해 알 수 있다.
premitive parameters: passed by value
object parameters passed by reference
function changeName(obj) {
obj.name = 'coder';
}
const sue = { name: 'sue' };
changeName(sue);
console.log(sue);
= name: "coder"
function showMessage(message, from = 'unknown') {
console.log(`${message} by ${from}`);
}
showMessage('Hi!');
function printAll(...args) {
for (let i = 0; i <args.length; i++) {
console.log(args[i]);
}
-------------- 간단하게 하려면 ---------------
for (const arg og args)
console.log(arg);
--------------더 간단하게 하려면--------------
args.forEach((arg) => console.log(arg));
}
printAll('sue', 'sujeong' 'coding')
=출력 결과는 sue / sujeong . coding 각각 하나씩 나온다.
let globalMessage = 'global' // global variable
function printMessage() {
let message = 'hello';
console.log(message); // local variable
console.log(globalMessage);
function pruntAnother(){
console.log(message);
let childMessage = 'hello'; ->자식 함수는 부모 함수에 정의된 변수에 접근을 하면 에러창이 뜬다.
}
}
printMessage();
:밖에서는 안이 보이지 않고 안에서만 밖을 볼 수 있다.
{블럭}안에 변수를 선언하게 되면 지역 변수
지역적이기 때문에 지연 안에서만 접근이 가능하다.
밖에서 출력하게 되면 에러 발생
function sum(a, b) {
return a + b;
}
const result = sum(1, 2); //3
console.log(`sum: ${sum(1, 2)}`);
function upgradeUser(user) {
if (user.point > 10) {
//long upgrade logic...
}
}
function upgradeUser(user) {
if (user.point <= 10) {
return;
//long upgrade logic...
}
}
출처: 드림코딩 자바스크립트 기초 강의 (ES5+)