Question

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.

Was it helpful?

Solution

Short answer:

typeof has a special case for unresolvable references; it explicitly returns undefined if the reference is unresolvable.

Long answer:

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:

  1. Let val be the result of evaluating UnaryExpression.
  2. If Type(val) is Reference, then
    1. If IsUnresolvableReference(val) is true, return "undefined".
    2. Let val be GetValue(val).
  3. 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)

  1. If Type(V) is not Reference, return V.
  2. Let base be the result of calling GetBase(V).
  3. If IsUnresolvableReference(V), throw a ReferenceError exception.
  4. If IsPropertyReference(V), then
    [...]

See the spec.

OTHER TIPS

someVariable is declared not initialized.But notDeclared is not declared..

someVariable does not contain any default value .But notDeclared is not avialable.

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.

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

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