Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does javascript have a concept like APIs

Tags:

javascript

I have mainly programmed in java with almost no javascript knowledge.
My question is whether javascript allows usage of APIs. For example I have a javascript application, I want some functions to be exposed to it like a middleware API set. This middleware can be in javascript too. I want to compartmentalize the application and middleware functionality. I will be implementing both the application and the middleware. Is this a valid use case or am I going about it the wrong way.

like image 996
bobby Avatar asked Jun 18 '26 02:06

bobby


1 Answers

An API is an abstract concept and JavaScript, like any programming language, allows the definition and use of API.

To define API, with clear separation of public functions from internal fields and functions, a popular pattern is the module pattern based on a IIFE.

Here's an example, in which you can see private data, a private function, and 3 public functions.

var countLib = (function(){
   var count = 0;
   var add = function(a) { count += a };
   return {
        getCount : function() { return count },
        increment : function() { add(1) },
        decrement : function() { add(-1) }
   }
})();

It allows you to do

countLib.increment();
var count = countLib.getCount(); // gets 1

The count internal value and the add function aren't exposed.

This pattern is used in many popular libraries. A frequent variant used in jQuery lets the library assign itself in the context :

(function(window){
   var count = 0;
   var add = function(a) { count += a };
   window.countLib = {
        getCount : function() { return count },
        increment : function() { add(1) },
        decrement : function() { add(-1) }
   }
})(window);

This has the minor advantage of enabling minifiers to reduce the window name and it also lets the library assign more than one name (for example "jQuery" and "$").

This example shows also the premises of another useful pattern, the namespace : an essential part of making things clear is in defining dedicated name space, which are built using properties :

 myLib = myLib || {};
 myLib.mySubLib1 = (function(){
      ...
 })();

Here, many files can have the same pattern : all of them would initialize myLib at the first line if it doesn't exist.

You'll usually combine those patterns to build a good looking library with minimal conflict risks (i.e. without defining global vars) and without exposing too much of its internals so that you can make the implementation evolve.

For more complex API, you can also define classes.

like image 86
Denys Séguret Avatar answered Jun 19 '26 17:06

Denys Séguret



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!