What does the term typeof module mean in javascript?

Asked

Viewed 281 times

3

What the term "typeof module" means 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)}
  • 1

    Tip: this code is not the easiest to read because it was minified. So, if you want to understand it, first of all it is better to go through some automatic reformatting tool.

  • THANK YOU!! I searched this tool all over the web and did not find, I am very grateful for your comment!!

  • Even after going through there the code is nothing readable. Compare with the ~25 lines of code of the original (lines 15-41).

2 answers

6


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

The operator typeof says what is the type of a variable. If it does not exist, the value of that 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 code "object"==typeof module checks the type of the variable module and compares with "object". If it is true, it is because this variable exists and is an object, if it is false it is probably because it does not exist (although it may exist and have another type). In the quoted expression, 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 the &&.

3

typeof is a javascript operator that allows you to see 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 a little further on:

&& "object" == typeof module.exports

Knowing that module is an object, we will now check whether 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");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.