# 오늘 한 일
one function === one thing
naming할 때는 역할을 명시할 것(동사형태)
function printAll(message) { conosle.log(message); }
바닐라 스크립트는 message의 타입을 string이나 number로 특정할 수 없기 때문에 오류가 발생할 여지가 있다. 이러한 문제를 해결하기 위해 타입스크립트가 개발되었다.
function log(message) { console.log(message); }
function log(message: string) { console.log(message); }
영어로 비유하면 one, another, others 중에서 others.
아래의 예시에서 parameter a가 one, parameter b가 another이라면 ...manyMoreArgs가 others.
a, b와는 달리 배열 형태로 값을 반환한다는 특징이 있다.
function myFun(a, b, ...manyMoreArgs) { console.log("a", a); console.log("b", b); console.log("manyMoreArgs", manyMoreArgs); } myFun("ellie", "leezche", "dream", "outgoing"); // 결과값: // a, ellie // b, leechze // manyMoreArgs, [dream, outgoing]
* 응용버전 function printAll(...args) { ① for(let i = 0; i < args.length; i++) { console.log(args[i]); } ② for(const arg of args) { console.log(args[i]); } ③ args.forEach((arg) => console.log(arg)); } printAll('dream', 'coding', 'ellie'); // 결과값: dream / coding / ellie
객체 밖에서는 객체 내부에 있는 변수를 사용할 수 없지만, 객체 내부에서는 밖에 있는 변수를 사용할 수 있다.
function printAll(writer) { let a = "document"; console.log(`${a} by ${writer}`) } let b = "paper"; console.log(b); // 결과값: paper console.log(a); // 결과값: error
1부터 100까지 기록하는데 1 ~ 10까지는 필요가 없다면 return을 사용하여 연산 속도를 단축시킬 필요가 있다.
//bad function upgradeUser(user) { if(user.point > 10) { console.log(user.point); } } //good function upgradeUser(user) { if(user.point <= 10) { return; } else { console.log(user.point); }
hoisting 가능
area(20, 40); function area(width, height){ return width * height; }
hoisting 불가
const area = function(width, height){ return width * height; } area(10, 30);
this의 쓰임새가 선언식이나 표현식과는 다르다.
const area = (width, height) => { return width * height; }
const Size = weight => { return weight/3; }
const Size = weight => weight / 3; (화살표 함수 + 삼항 연산자) const plantNeedsWater = day => day === 'Monday' ? true : false;
함수를 바로 실행할 수 있다.
(function hello(){ console.log('hello'); })();