Javascript Developer JSE 40 01 · Free Practice Question Easy
Question 16
Q435 - Error Handling
Analyze the following code:
- 'let msg = "Hello World"';
- console.log(msg);
What exception will be thrown as a result of its execution attempt?
-
A
- TypeError
-
B
- ReferenceError
-
C
- RangeError
-
D
- SyntaxError
Reveal correct answer
Correct answer: B
Explanation
Topic: ReferenceError
Try it yourself:
- 'let msg = "Hello World"';
- console.log(msg); // Uncaught ReferenceError: msg is not defined
Explanation:
The whole first line is a string
and therefore msg is never defined.
The ReferenceError object represents an error when a variable that
doesn't exist (or hasn't yet been initialized) in the current scope is referenced.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError
(There is a similar question Q635.)
Q435 (Please refer to this number, if you want to write me about this question.)
A. TypeError occurs when an operation is performed on a value of the wrong type. In this code snippet, there are no operations that involve incorrect data types, so a TypeError will not be thrown as a result of its execution attempt.
B. The code snippet is attempting to log the value of the variable msg, which is declared using the let keyword. If the variable msg is not defined or is out of scope at the time of execution, a ReferenceError will be thrown.
C. RangeError occurs when a value is not in the set or range of allowed values. In this code snippet, there are no operations that involve ranges or sets of values, so a RangeError will not be thrown as a result of its execution attempt.
D. SyntaxError occurs when there is a mistake in the syntax of the code. In this code snippet, there are no syntax errors present, so a SyntaxError will not be thrown as a result of its execution attempt.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
