Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is 'typeof define === 'function' && define['amd']' used for?

Tags:

javascript

What purpose does the following code serve? What does factory function do here? Here root is window object. Is factory a default java script function? In what kind of scenarios this type of code can be used. This code is from toggle.js from Simon Tabor. Zepto and ender are libraries. Is this mostly used in libraries.

   if (typeof define === 'function' && define['amd']) {
        define(['jquery'], factory);
     } else {
      factory(root['jQuery'] || root['Zepto'] || root['ender'] || root['$']|| $);
    }
like image 520
Suresh kumar Avatar asked Jun 20 '15 11:06

Suresh kumar


People also ask

How do you define a function in JavaScript?

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)

What is typeof function in JavaScript?

Typeof in JavaScript is an operator used for type checking and returns the data type of the operand passed to it. The operand can be any variable, function, or object whose type you want to find out using the typeof operator.

What will be the output of typeof null?

In JavaScript null is "nothing". It is supposed to be something that doesn't exist. Unfortunately, in JavaScript, the data type of null is an object. You can consider it a bug in JavaScript that typeof null is an object.

Which type does the typeof operator return?

The operator returns the data type. There are six possible values that typeof returns: object, boolean, function, number, string, and undefined.


1 Answers

This code checks for the presence of require.js, a JavaScript dependency management library.

If 'define' is not undefined and it is a function and 'amd' (asynchronous module definition) is also defined then the code assumes that require.js is in play.

If this is so then it defines 'factory' and passes jQuery to it as a dependency. Otherwise it sets up the dependencies that the code needs by attaching them to the root object.

As for what 'factory' is: it is not defined by the Javascript framework, it will be a function in the same file most likely. It will take the parameter jQuery.

like image 153
Aran Mulholland Avatar answered Oct 17 '22 21:10

Aran Mulholland