이번 Basic CS Sections에서 배운 내용은 ES6 문법, 객체 지향 프로그래밍(OOP), 자료 구조(Data Structure), 알고리즘의 꽃인 N-Queens가 있다.
이 중 오늘은 ES6 문법 중 arrow function에 대해 복습하도록 하겠다.
function 대신 화살표 (=>
, fat arrow)를 사용하여 기존의 함수를 정의하는 방식보다 간략하게 함수를 정의할 수 있는 방법이다.
표현 뿐만 아니라 내부 동작도 기본의 함수보다 간략하다.
화살표 함수는 함수 표현식으로만 정의할 수 있다!
const multiply = (x, y) => x * y;
multiply(3,4); // 12
const arrow = (x, y) => { ... };
const arrow = x => { ... };
const arrow = () => { ... };
const power = x => x ** 3;
power(3); // 27
// 위의 코드와 동일한 표현
const power = x => { return x ** 3; };
const arrow = () => const x = 2; // Uncaught SyntaxError: Unexpected token 'const'
// 따라서
const arrow = () => { return const x = 2; };
// 혹은
const arrow = () => { const x = 2; };
//이렇게 표현이 가능하다.
[1,2,3,4].map(function (V) {
return v * 2;
});
// 위의 문장을 화살표 함수를 사용하면 이렇게 표현이 가능하다.
[1,2,3,4].map(v => v * 2); // [2,4,6,8]
완전 간결하다!
<화살표 함수>
const Foo = () => {};
new Foo(); // Uncaught TypeError: Foo is not a constructor
Foo.hasOwnProperty('prototype'); // false
<일반 함수>
const Foo = function() {}; // undefined
new Foo(); // Foo {}
Foo.hasOwnProperty('prototype'); // true
<화살표 함수>
const arrow = (a, a) => a + a; // Uncaught SyntaxError: Duplicate parameter name not allowed in this context
<일반 함수> : 중복된 매개변수 이름을 선언해도 에러가 발생하지 않는다.
(단, strict mode에서 선언할 경우는 예외다.)
function normal(a, a) {
return a + a;
}
console.log(normal(1,2)); // 4