[JavaScript] Function vs Const
React๋ก ์น ํ๋ก ํธ์๋ ๊ฐ๋ฐ์ ํ๋ฉด์ ์ปดํฌ๋ํธ๋ฅผ function(){} ํํ๋ก ์ ์ธํ๊ธฐ๋ ํ๊ณ const=()=>{} ํํ๋ก ์ ์ธํ๊ธฐ๋ ํ๋ค. ๊ทธ๋ ๋ค๋ฉด ๋ ๋ฐฉ์์ ์ฐจ์ด์ ์ ๋ฌด์์ธ์ง, ๋ ๋์ ๋ฐฉ์์ด ์๋ค๋ฉด ์ด๋ค ๊ฒ์ธ์ง ์์๋ณด๋๋ก ํ์.
๋จผ์ ๋ ๋ฐฉ์์ ์ฐจ์ด์ ์ ํฌ๊ฒ ๋ ๊ฐ์ง์ด๋ค.
- ํธ์ด์คํ ๊ฐ๋ฅ ์ฌ๋ถ
- export default ๋์ ์ ์ธ ์ฌ๋ถ
* ํธ์ด์คํ (hoisting) : ์ธํฐํ๋ฆฌํฐ๊ฐ ์ฝ๋๋ฅผ ์คํํ๊ธฐ ์ ์ ํจ์, ๋ณ์, ํด๋์ค ๋๋ ์ํฌํธ(import)์ ์ ์ธ๋ฌธ์ ํด๋น ๋ฒ์์ ๋งจ ์๋ก ์ด๋์ํค๋ ๊ณผ์
ํธ์ด์คํ ๊ฐ๋ฅ ์ฌ๋ถ
Function() ์ผ๋ก ์ ์ธํ๋ ๋ฐฉ์์ ํธ์ด์คํ ์ด ๊ฐ๋ฅํ๊ธฐ ๋๋ฌธ์ ํจ์ ์คํ ์ฝ๋ ๋ฐ์ ์ ์ธ์ ํด์ฃผ๋ ๊ฒ์ด ๊ฐ๋ฅํ๋ค.
๋ฐ๋ฉด์ Const=()=>์ ๊ฐ์ ๊ฒฝ์ฐ ํธ์ด์คํ ์ด ๋ถ๊ฐ๋ฅํ๊ธฐ ๋๋ฌธ์ ๋จผ์ ์ ์ธ์ ํด์ฃผ๊ณ ๊ทธ ๋ฐ์์ ํจ์ ์คํ์ ํด์ค์ผ ํ๋ค.
์ด ๋๋ถ์ Function()๊ณผ ๊ฐ์ ํจ์ํ ์ ์ธ์ ๊ฒฝ์ฐ ์ ์ธ๋ถ๋ ์ฝ๋ ํ๋จ์ ๋๊ณ , ๋ฉ์ธ ๋ก์ง๋ง ์ ๋ถ๋ถ์ ๊ตฌํํด์ฃผ๋ฉด์ ์ฝ๋ ๊ฐ๋ ์ฑ์ ๋ ๋์ผ ์ ์๋ค.
1. Const=()=>{}
const tryDoTheThing = () => {
console.log(`This is me trying to be awesome ${getAwesome()}`)
}
// "getAwesome is not defined", because it is referenced too early
tryDoTheThing() // comment to see the rest work
const doTheThing = () => {
console.log(`This is awesome! ${getAwesome()}`)
}
doTheThing() // prints
2. function(){}
/*
Function declarations are given two passes, where the first lifts them to
the top of the namespace, allowing "out of order" usage
*/
doTheThing();
function doTheThing() {
console.log(`This is awesome number ${getAwesome()}`)
}
function getAwesome() {
return (+((Math.random() * 10000).toString().split('.')[0]))
}
export default ๊ฐ๋ฅ ์ฌ๋ถ
// ์ ์ธ๋ฌธ์ ํจ์ ์ ์ธ๊ณผ export default๋ฅผ ๋์์ ํ ์ ์๋ค.
export default function Foo(){}
// ํํ์์ ๋ถ๊ฐ๋ฅํ๋ค
export default const Foo = () => {} // error
// named export๋ ๊ฐ๋ฅํ๋ค
export const Foo = () => {}
export default๋ฅผ ๋ถ์ฌ์คฌ๋ค๋ ๊ฑด ํด๋น ์ฝ๋์ ๋ฉ์ธ ๋ก์ง์ด๋ผ๋ ๊ฒ์ ์๋ฏธํ๋ค.
๋ค๋ฅธ ์ปดํฌ๋ํธ์์ ํด๋น ์ปดํฌ๋ํธ๋ฅผ ๋ถ๋ฌ์ฌ ๋๋ export ๋ง์ด ๋ถ์ด์๋ ์ปดํฌ๋ํธ๋ import {} from "./.." ํํ๋ก ๋ถ๋ฌ์ค์ง๋ง, export default๊ฐ ๋ถ์ด์๋ ์ปดํฌ๋ํธ import name from "./..";์ผ๋ก ๋ถ๋ฌ์ฌ ์ ์๋ค.
์ ์ธ๊ณผ ๋์์ export default๋ฅผ ๋ถ์ผ ์ ์๋ ๊ฑด function ํ์์ผ๋ก ์ ์ธํ๋ ๊ฒฝ์ฐ์ด๊ณ , const=()=>๋ export๋ง ๋ถ์ผ ์ ์๋ค.