3

When I execute below code , it prints "undefined" two times. I was expecting that it would raise error since variable is not defined and also there is use strict' statement in the top.

'use strict';
var a;

console.log(typeof a);
console.log(typeof b);

Can anyone explain why it is not raising an error ?

refactor
  • 13,954
  • 24
  • 68
  • 103
  • 1
    because that's how it works... – Alnitak Apr 13 '16 at 09:50
  • Simply `undefined` means that the variable isn't yet defined, that's the normal behavior. – cнŝdk Apr 13 '16 at 09:51
  • 2
    'typeof' never raises error: if a variable is undefined, it returns "undefined". By design. – MarcoS Apr 13 '16 at 09:52
  • This is not related to `node.js`.. Will behave exactly same in the browser! – Rayon Apr 13 '16 at 09:53
  • 1
    related, if not duplicate: [Using typeof vs === to check undeclared variable produces different result](http://stackoverflow.com/q/31671887/1048572), [How does typeof circumvent the ReferenceError when supplied an undeclared variable identifier?](http://stackoverflow.com/q/29155472/1048572), [How can I determine if a JavaScript variable is defined in a page?](http://stackoverflow.com/q/138669/1048572) – Bergi Apr 13 '16 at 11:25

3 Answers3

2

In fact in JavaScript undefined means that the variable isn't yet defined, so basically :

  • typeof a returns undefined because the variable a was only declared but not initialized yet (there's no value assigned to it).

  • And typeof b returns undefined because the variable b is not yet declared, so isn't defined.

And if there's no value assigned to a variable, it gets the type undefined because as type can't be determined.

So if you check the MDN typeof specification you will see that :

The typeof operator returns a string indicating the type of the unevaluated operand, and if you see types table you can see that undefined is a primitive type and one of the possible return values of typeof.

Examples:

And you can see in the Examples section, the undefined return:

// Undefined

typeof undefined === 'undefined';

typeof declaredButUndefinedVariable === 'undefined';

typeof undeclaredVariable === 'undefined';

Note:

And as stated in comments this is only related to JavaScript syntax and doesn't have anything to do with nodejs.

Community
  • 1
  • 1
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
-1

You don't use a function from "a", nor do you use any functions wich excepts a parameter, wich isn't undefined. Typeof only checks for the memory location of the variable.

Bálint
  • 4,009
  • 2
  • 16
  • 27
-1

undefined is a primitive data type,

and that's one of the possible options the typeof operator can return,

the other options it can return are:

  • boolean
  • number
  • string
  • function
  • object
  • symbol
maioman
  • 18,154
  • 4
  • 36
  • 42