์๋ฐ์คํฌ๋ฆฝํธ์๋ expression๊ณผ statement๋ผ๋ ์ฃผ์ํ ๋ ๊ฐ์ง ๊ตฌ๋ฌธ ์นดํ ๊ณ ๋ฆฌ(syntactic categories)๊ฐ ์๋ค.
expression์ statement์ฒ๋ผ ๋์ํ ์ ์์ง๋ง statement๋ expression์ฒ๋ผ ๋์ํ ์ ์๋ค.
expression์ ๊ฐ์ ๋ฐํํ๋ ๊ตฌ๋ฌธ ์ฆ, ๊ฐ์ผ๋ก ํ๊ฐ๋ ์ ์๋ ์์ด๋ค.
2 + 2 * 3 / 2
(Math.random() * (100 - 20)) + 20
1+1, 2+2, 3+3
// "," ์ผํ๋ฅผ ์ฌ์ฉํด ์ฌ๋ฌ ํํ์์ ๋์ด ํ ์ ์๋ค. ๊ทธ๋ฌ๋ ๋ง์ง๋ง ํํ์์ ๊ฐ๋ง ๋ฐํํ๋ค.expression์ state๋ฅผ ๋ณ๊ฒฝํ์ง ์๋๋ค.
์๋ ์ฝ๋ ์์ ์ expression์์ assignedVariable์ด๋ผ๋ state์ +, - ์ฐ์ฐ์ ํ์ง๋ง ํด๋น ์ฐ์ฐ์ ๋ฐํ ๊ฐ์๋ง ์ํฅ์ ์ค ๋ฟ ์ค์ assignedVariable ๊ฐ์๋ ์ํฅ์ ์ฃผ์ง ์๋๋ค.
const assignedVariable = 2; // statement, assignedVariable์ state
assignedVariable + 4 // expression,
assignedVariable - 10 // expression
console.log(assignedVariable) // 23 * 3 // expression
function multiply(n1, n2) {
n1 * n2;
}
const result = multiply(3, 3); //expression, undefined
// multiply(3,3)์ undefined๋ฅผ ๋ฐํํ๋ฏ๋ก ์ด ๋ํ ํํ์์ด๋ค.statement๋ ํ๋ก๊ทธ๋จ์ ๊ตฌ์ฑํ๋ ๊ธฐ๋ณธ ๋จ์์ด์ ์ต์ ์คํ ๋จ์์ด๋ค. ๋ํ statement๋ ๊ฐ์ด ํ์ํ ๊ณณ์ ์ฌ์ฉ๋ ์ ์๋ ๋ช ๋ น์ด๋ ์ง์ ๊ตฌ๋ฌธ์ ์๋ฏธํ๋ค.
์ฆ, statement๋ ํจ์์ ์ธ์, ํ ๋น ์ ์ค๋ฅธ์ชฝ ๋ถ๋ถ, ํผ์ฐ์ฐ์, ๋ฐํ ๊ฐ ๋ฑ์ผ๋ก ์ฌ์ฉ๋ ์ ์๋ค.
console.log(if(true) {3+3});
// Uncaught SyntaxError: Unexpected token 'if'์๋ฅผ ๋ค์ด ์ฝ์์ ์ ์ฝ๋๋ฅผ ์ ๋ ฅ ํ ์คํํ ๊ฒฝ์ฐ ์ฝ์์ ์๋ฌ๊ฐ ์ถ๋ ฅ ๋ ๊ฒ์ด๋ค.
์๋ฐ์คํฌ๋ฆฝํธ์์์ statement์ ์ข ๋ฅ ์๋์ ๊ฐ๋ค.
ifif-elsewhiledo-whileforswitchfor-in- with(deprecated)
- debugger
- variable declaration
expression statement๋ statement์ง๋ง ๊ฐ์ผ๋ก ํ๊ฐ๋ ์ ์๋ expression์ ์กฐ๊ฑด์ ๋ง์กฑํ๋ statement๋ฅผ ์๋ฏธํ๋ค.
let x; // ๊ฐ์ผ๋ก ํ๊ฐ๋ ์ ์์ผ๋ฏ๋ก expression์ด ์๋ statment์ด๋ค.
x = 1 + 2; // ๊ฐ์ผ๋ก ํ๊ฐ ๋ ์ expression์ด๋ฉด์ statement์ ์กฐ๊ฑด๋ ๋ง์กฑํ๋ค.
const y = x = 3; // expression statemet๋ ๊ฐ์ผ๋ก ์ฌ์ฉ๋ ์ ์๋ค.function declaration์ด๋ function ํค์๋๋ฅผ ์ฌ์ฉํ ํจ์ ์ ์ธ์์ด๋ค.
function declaration์ผ๋ก ์ ์ธ๋ ํจ์๋ ํฅํ ์ฌ์ฉ์ ์ํด(saved for later use) ์ ์ฅ ๋์๋ค๊ฐ, ํธ์ถ ๋ ๋ ์คํ๋๋ค. ๋ํ function declaration์ผ๋ก ์ ์ธ๋ ํจ์๋ ์ฝ๋๊ฐ ์คํ ๋๊ธฐ ์ ๋ก๋(ํจ์ ํธ์ด์คํ )๋๋ค.
alert(foo()); // Alerts 5
function foo() { return 5; }
// function foo()๋ function declaration์ด๋ฏ๋ก ํธ์ด์คํ
๋์ด ํจ์ ์ ์ธ์ด ํธ์ถ๋ณด๋ค ๋ท ๋ผ์ธ์ ์์นํ๋๋ผ๋ ์ ์์ ์ผ๋ก ์คํ๋๋ค.function expression์ ํํ์์ ์ฌ์ฉํ ํจ์ ์ ์ธ์ด๋ค.
function exrpression์ ๋ณ์์ ์ ์ฅ๋ ์ ์์ผ๋ฉฐ ์ ์ฅ๋ ํ ํจ์๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ์๋๋ก ์ฌ์ฉ๋ ์ ์๋ค.
Function declaration๊ณผ ๋ฌ๋ฆฌ function expression์ผ๋ก ์ ์๋ ํจ์๋ ํจ์ ํธ์ด์คํ ์ด ๋์ง ์๊ณ ๋ณ์ ํธ์ด์คํ ์ผ๋ก ๋์ํ๋ค.
alert(foo()); // Uncaught ReferenceError: foo is not defined
const foo = function () { return 5; }alert(foo()); // Uncaught ReferenceError: foo is not defined
const foo = () => 5;๋ค๋ฅธ ํจ์์ ์ธ์๋ก ์ฌ์ฉ, ํด๋ก์ , ์ฆ์์คํํจ์(IIFE) ๋ฑ์ ๋ชฉ์ ์ผ๋ก ํจ์๋ฅผ ์ ์ธํ ๋์๋ function declaration๋ณด๋ค function expression์ผ๋ก ํจ์๋ฅผ ์ ์ธํ๋ ๊ฒ์ด ๋ ์ ์ฉํ๋ค.
Reference