๐Ÿ“ŒLanguage/JavaScript

[Deep Dive] ES6 ํ•จ์ˆ˜์˜ ์ถ”๊ฐ€ ๊ธฐ๋Šฅ (ํ™”์‚ดํ‘œ ํ•จ์ˆ˜, REST ํŒŒ๋ผ๋ฏธํ„ฐ, ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ธฐ๋ณธ๊ฐ’)

hellohailie 2022. 12. 21. 23:58

โœ”๏ธ ์ด๋ฒˆ ์ •๋…์„ ํ†ตํ•ด ์•Œ๊ฒŒ ๋œ ๊ฒƒ
ํ™”์‚ดํ‘œ ํ•จ์ˆ˜
REST ํŒŒ๋ผ๋ฏธํ„ฐ
๋งค๊ฐœ๋ณ€์ˆ˜ ๊ธฐ๋ณธ๊ฐ’

 


โœ”๏ธ ํ™”์‚ดํ‘œ ํ•จ์ˆ˜

ํ•จ์ˆ˜ ํ‘œํ˜„์‹์œผ๋กœ ์ •์˜ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. 

ํ•จ์ˆ˜ ๋ชธ์ฒด๊ฐ€ ํ•˜๋‚˜์˜ ๋ฌธ์œผ๋กœ ๊ตฌ์„ฑ๋œ๋‹ค๋ฉด ํ•จ์ˆ˜ ๋ชธ์ฒด๋ฅผ ๊ฐ์‹ธ๋Š” ์ค‘๊ด„ํ˜ธ {}๋ฅผ ์ƒ๋žตํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 

// concise body
const power = x => x ** 2;

// ์œ„ ํ‘œํ˜„์€ ๋‹ค์Œ๊ณผ ๋™์ผํ•˜๋‹ค.
// block body
const power = x => { return x ** 2; };

power(2); // -> 4

 

๋‹จ, ํ•จ์ˆ˜ ๋ชธ์ฒด๊ฐ€ ํ•˜๋‚˜์˜ ๋ชธ์œผ๋กœ ๊ตฌ์„ฑ๋œ๋‹ค ํ•ด๋„ ํ•จ์ˆ˜ ๋ชธ์ฒด์˜ ๋ฌธ์ด ํ‘œํ˜„์‹์ด ์•„๋‹Œ ๋ฌธ์ด๋ผ๋ฉด ์ค‘๊ด„ํ˜ธ๋ฅผ ์ƒ๋žตํ•  ์ˆ˜ ์—†๋‹ค. 

const arrow = () => const x = 1; // SyntaxError: Unexpected token 'const'

// ์œ„ ํ‘œํ˜„์€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ํ•ด์„๋œ๋‹ค.
const arrow = () => { return const x = 1; };

 

๊ฐ์ฒด ๋ฆฌํ„ฐ๋Ÿด์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒฝ์šฐ ๊ฐ์ฒด ๋ฆฌํ„ฐ๋Ÿด์„ ์†Œ๊ด„ํ˜ธ ()๋กœ ๊ฐ์‹ธ ์ฃผ์–ด์•ผ ํ•œ๋‹ค. 

const create = (id, content) => ({ id, content });

// ์œ„ ํ‘œํ˜„์€ ๋‹ค์Œ๊ณผ ๋™์ผํ•˜๋‹ค.
const create = (id, content) => { return { id, content }; };

create(1, 'JavaScript'); // -> {id: 1, content: "JavaScript"}

 

ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋Š” ์ฝœ๋ฐฑํ•จ์ˆ˜๋กœ์„œ ์ •์˜ํ•  ๋•Œ ์œ ์šฉํ•˜๋‹ค.

// ES5
[1, 2, 3].map(function (v) {
  return v * 2;
});

// ES6
[1, 2, 3].map(v => v * 2); // -> [ 2, 4, 6 ]

 


โœ”๏ธ REST ํŒŒ๋ผ๋ฏธํ„ฐ

ํ•จ์ˆ˜์— ์ „๋‹ฌ๋œ ์ธ์ˆ˜๋“ค์˜ ๋ชฉ๋ก์„ ๋ฐฐ์—ด๋กœ ์ „๋‹ฌ๋ฐ›๋Š”๋‹ค. 

ํ•จ์ˆ˜ ์ •์˜ ์‹œ ์„ ์–ธํ•œ ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ฐœ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ํ•จ์ˆ˜ ๊ฐ์ฒด์˜ length ํ”„๋กœํผํ‹ฐ์— ์˜ํ–ฅ์„ ์ฃผ์ง€ ์•Š๋Š”๋‹ค. 

function foo(param, ...rest) {
  console.log(param); // 1
  console.log(rest);  // [ 2, 3, 4, 5 ]
}

foo(1, 2, 3, 4, 5);
console.log(foo.length) // 1

function bar(param1, param2, ...rest) {
  console.log(param1); // 1
  console.log(param2); // 2
  console.log(rest);   // [ 3, 4, 5 ]
}

bar(1, 2, 3, 4, 5);
console.log(bar.length) // 2

 


โœ”๏ธ ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ธฐ๋ณธ๊ฐ’

์ธ์ˆ˜๊ฐ€ ์ „๋‹ฌ๋˜์ง€ ์•Š์€ ๋งค๊ฐœ๋ณ€์ˆ˜์˜ ๊ฐ’์€ undefined์ด์ง€๋งŒ ES6์—์„œ ๋„์ž…๋œ ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ธฐ๋ณธ๊ฐ’์„ ์‚ฌ์šฉํ•˜๋ฉด ํ•จ์ˆ˜ ๋‚ด์—์„œ ์ˆ˜ํ–‰ํ•˜๋˜ ์ธ์ˆ˜ ์ฒดํฌ ๋ฐ ์ดˆ๊ธฐํ™”๋ฅผ ๊ฐ„์†Œํ™”ํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

ES5

function sum(x, y) {
  // ์ธ์ˆ˜๊ฐ€ ์ „๋‹ฌ๋˜์ง€ ์•Š์•„ ๋งค๊ฐœ๋ณ€์ˆ˜์˜ ๊ฐ’์ด undefined์ธ ๊ฒฝ์šฐ ๊ธฐ๋ณธ๊ฐ’์„ ํ• ๋‹นํ•œ๋‹ค.
  x = x || 0;
  y = y || 0;

  return x + y;
}

console.log(sum(1, 2)); // 3
console.log(sum(1));    // 1

ES6

function sum(x = 0, y = 0) {
  return x + y;
}

console.log(sum(1, 2)); // 3
console.log(sum(1));    // 1

 

 

 

๐Ÿ‘ฉ‍๐Ÿ’ป ๋ชจ๋˜ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ Deep Dive๋ฅผ ์ •๋…ํ•˜๊ณ  ์ œ๊ฐ€ ์ดํ•ดํ•œ ๋‚ด์šฉ์„ ์ •๋ฆฌํ•œ ๊ธ€์ž…๋‹ˆ๋‹ค ๐Ÿ‘ฉ‍๐Ÿ’ป