Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding Javascript Typeof

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 ?

like image 888
refactor Avatar asked Dec 06 '25 17:12

refactor


1 Answers

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.

like image 173
cнŝdk Avatar answered Dec 08 '25 07:12

cнŝdk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!