What does the term typeof module mean in javascript?

3

What does the term "typeof module" mean in javascript?

Example:

function(c,p){"object"==typeof module&&"object"==typeof module.exports?module.exports=c.document?p(c,!0):function(c){if(!c.document)throw Error("jQuery requires a window with a document");return p(c)}
    
asked by anonymous 07.07.2017 / 00:38

2 answers

6

This code snippet is testing whether the module variable exists or not - probably to detect whether the code is running in browser or in a Node.js environment.

The typeof operator tells you what kind of a variable. If it does not exist, the value of this expression is undefined :

var a = 10;
var b = "teste";
var c = { foo:"bar" };

console.log(typeof a); // "number"
console.log(typeof b); // "string"
console.log(typeof c); // "object"
console.log(typeof d); // "undefined"

In this example, the "object"==typeof module code checks the type of the module variable and compares it to "object" . If it is true, it is because this variable exists and is an object, if it is false then it probably does not exist (although it may exist and have another type). In the expression quoted, a false result will cause the command to stop there (short circuit), while a true one will execute the code that is to the right of && .

    
07.07.2017 / 00:46
3

typeof is a javascript operator that allows you to view the type of a variable.

"object"==typeof module

Or usually written as typeof module == "object" checks if the module variable is an object.

The same thing goes a little further:

&& "object" == typeof module.exports

Knowing that module is an object, let's now check that module.exports is also an object.

Exemplification:

var var1 = "ola";
var var2 = 10;
var var3 = { };

console.log(typeof var1);
console.log(typeof var2);
console.log(typeof var3);

console.log(typeof var2 == "object");
console.log(typeof var3 == "object");
    
07.07.2017 / 00:46