Reputation: 944
The code is:
var someVariable; // this variable is declared but not initialised...
alert(typeof someVariable); // alerts 'undefined'
alert(typeof notDeclared); // also alerts 'undefined' irrespective
// of the fact it has not been declared..
It seems a bit confusing. Now, if I do
alert(someVariable); // again alerts 'undefined'
alert(notDeclared); // causes an error
jsFiddle link: http://jsfiddle.net/gjYZt/2/
If 'typeof notDeclared' is undefined, then when I alert 'notDeclared', it should also alert 'undefined' instead of giving an error.
Upvotes: 2
Views: 133
Reputation: 99921
typeof
has a special case for unresolvable references; it explicitly returns undefined
if the reference is unresolvable.
The typeof operator has a special case for unresolvable references:
11.4.3 The typeof Operator
The production UnaryExpression :
typeof
UnaryExpression is evaluated as follows:
- Let val be the result of evaluating UnaryExpression.
- If Type(val) is Reference, then
- If IsUnresolvableReference(val) is
true
, return "undefined
".- Let val be GetValue(val).
- Return a String determined by Type(val) according to Table 20.
On the other hand, the internal GetValue(V)
function, which is used everywhere in javascript, including for retrieving the value of a varialbe, throws a ReferenceError if the reference is unresolvable:
8.7.1 GetValue (V)
- If Type(V) is not Reference, return V.
- Let base be the result of calling GetBase(V).
- If IsUnresolvableReference(V), throw a
ReferenceError
exception.- If IsPropertyReference(V), then
[...]
See the spec.
Upvotes: 3
Reputation: 347
the operator typeof returns the type of the operand.
This list summarizes the possible return values of typeof
Type Result
Undefined "undefined"
Null "object"
Boolean "boolean"
Number "number"
String "string"
Host object (provided by the JS environment) Implementation-dependent
Function object (implements [[Call]] in ECMA-262 terms) "function"
E4X XML object "xml"
E4X XMLList object "xml"
Any other object "object"
if yout alert return undefined that's because your variable type is undifined.
Regards
Upvotes: 0
Reputation: 437434
When I do 'alert(typeof notDeclared);', that should also give an error. Isn't it?
No, because the specification is clear that if the operand to typeof
is not resolvable, the result of typeof
must be undefined
(look at 2a).
When you try to evaluate an expression that is not resolvable such as notDeclared
in your example, you get a ReferenceError -- this is also according to the spec.
Upvotes: 1
Reputation: 40338
someVariable
is declared not initialized
.But notDeclared
is not declared..
someVariable
does not contain any default value .But notDeclared
is not avialable.
Upvotes: 2