자바스크립트 에러 (Error)

Seongkyun Yu·2020년 12월 7일
0

TIL - Javascript

목록 보기
20/28

기존 블로그에 작성한 내용을 velog로 이전한 글입니다


1. Error 요약


2. TypeError

TypeError 객체는 보통 값이 기대하던 자료형이 아니라서 연산을 할 수 없을 때 발생하는 오류입니다.
(MDN: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/TypeError)

변수 타입과 상관 없는 명령을 실행할 때 나오는 에러.

함수가 아닌데 함수처럼 호출한다던가 const로 선언된 변수에 재할당을 시도할때 발생한다.

const x = 1;

x(); // TypeError: x is not a function

x += 1; // TypeError: Assignment to constant variable.

x++; // TypeError: Assignment to constant variable.

하지만 놀랍게도 다음과 같이 쓰면 에러가 뜨지 않고 undefined를 뱉거나 무시한다.

const x = 1;

console.log(x.tip); // undefined

x.tip = "상상도 못한 정체"; // 그냥 무시해 버린다

console.log(x); // 1

세상에...


3. ReferenceError

ReferenceError 객체는 존재하지 않는 변수를 참조했을 때 발생하는 에러를 나타냅니다.
(MDN: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError)

선언하지 않은 변수를 참조할때 주로 발생한다.

console.log(y); // ReferenceError: y is not defined

if (true) {
  let i = 0;
}

console.log(i); // ReferenceError: i is not defined

스코프를 잘못 생각하거나 변수를 선언했다고 착각할 때 발생할 수 있는 오류이다.


4. SyntaxError

SyntaxError 객체는 문법적으로 유효하지 않은 코드를 해석하려고 시도할 때 발생하는 오류를 표현합니다.
(MDN: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError)

자바스크립트 문법에 맞지 않게 작성된 코드에서 나오는 오류이다.

eval("에러가 뜰까?"); // SyntaxError: Unexpected identifier
profile
FrontEnd Developer

0개의 댓글