Question

Considering the following code:

//the var Test has NOT been declared yet

console.log((typeof Test)); // "undefined"
console.log(Test); //"Uncaught ReferenceError: Test is not defined"

Why does the second console.log statement throw a ReferenceError and the first displays undefined.

Was it helpful?

Solution

Because test is undefined.

In that first console.log you're asking the system to tell you the type of a variable. So it looks through the current scope chain to find a reference to that variable so it may infer its type.

When it doesn't find the variable, it receives the undefined primitive. Which has a type, as I'm sure you've guessed, of undefined.

The second time you're asking it to print out the value of an undefined variable. Since the variable is not defined (there is no reference to it in the current scope chain), this is an error you're trying to ACCESS DATA that doesn't exist, not just infer its type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top