짹뚜 스튜디오

Expression vs Statement 본문

개발 공부/javascript

Expression vs Statement

짹뚜 2021. 12. 21. 14:03

해당 글은 모든 자바스크립트 개발자가 알아야 하는 33가지 개념에서 일곱 번째인 Expression vs Statement 항목을 공부하면서 간단하게 작성한 글이다.

Expression

값을 만들어내는 코드를 Expression (표현식)이라고 한다. 아래 코드들이 Expression의 예시이다.

2 + 3
Math.random()
1 == 2

Statement

어떤 동작을 수행하는 코드를 Statement 라고 한다. Statement는 값이 요구되는 곳에 사용될 수 없다.

foo1(if(true){return 5;}); // 에러가 발생한다.

자바스크립트에서 Statement은 다음과 같다.

 

  1. if
  2. if-else
  3. while
  4. do-while
  5. for
  6. switch
  7. for-in
  8. debugger
  9. varaible declaration (var, let, const)

Function Declaration and Expression

일반적으로 함수를 선언할 때는 다음과 같이 사용한다.

// Function Declaration
function foo1(){
	console.log("hello world!");
}

그러나 자바스크립트에서는 함수를 Expression 형태로 선언할 수 도있다.

// Function Expression
const foo1 = () => {
	console.log("Hello World!");
}

두 방식의 차이점은 호이스팅(Hoisting)에 있다. 호이스팅을 간단히 설명하자면 변수나 함수가 선언되기 전에 호출을 할 수 있는 것을 얘기한다. (자세한 내용은 다른 포스팅에서 다룰 예정이다.) Function Declaration 형식으로 함수를 선언하면 선언 전에도 해당 함수를 호출할 수 있지만 Function Expression 형식은 항상 선언 후에 호출해야 한다.

// Function Declaration
foo1();   // 에러 없이 실행 잘됨
function foo1(){
	console.log("hello world!");
}

// Function Expression
foo2();   // 에러 발생
const foo2 = () => {
	console.log("hello world!");
}

 

'개발 공부 > javascript' 카테고리의 다른 글

모듈  (0) 2021.12.22
IIFE (Immediately Invoked Function Expression)  (0) 2021.12.22
Scope (스코프)  (0) 2021.12.20
== vs === vs typeof  (0) 2021.12.20
Type Coercion (타입 변환)  (0) 2021.12.19
Comments