자바스크립트 에러 (Error)

Posted by Seongkyun Yu on 2020-03-11
Estimated Reading Time 1 Minutes
Words 204 In Total
Viewed Times

Error 요약

Error 종류 (https://en.hexlet.io/)


TypeError

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

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

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

1
2
3
4
5
6
7
const x = 1;

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

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

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

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

1
2
3
4
5
6
7
const x = 1;

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

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

console.log(x); // 1

세상에…


ReferenceError

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

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

1
2
3
4
5
6
7
console.log(y); // ReferenceError: y is not defined

if (true) {
let i = 0;
}

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

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


SyntaxError

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

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

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

If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !