Creating your own JavaScript Library

One of the phases I went through while learning about JavaScript was the intense desire to write my own library, similar to jQuery (but massively scaled down).

My library has gone through several major revisions — and more than one complete re-write, but now is exactly what I started out hoping it would be: functional, clean, small, and a solid learning experience.

I’d like to share what I learned from this project, and I hope you share back with me through the comments!

Finished project demo

Step 1: Identify the purpose of your library

This might just be one of the toughest parts of the whole process!  If you are to the point in your JavaScript knowledge that you would like to build your own library, than you’ve likely used jQuery, mooTools, Prototype, or any number of other popular libraries.  I use jQuery extensively in my projects, and know that it is very capable in many aspects, including: animation, user input validation, AJAX loading/submitting, event handling,  etc. Knowing this, it is tempting to have lofty goals for your own library. One piece of advice: Don’t. 

Pick one particular function, or aspect of web development/design that you would like your library to handle. Pick a niche need, and be happy with yourself when you fill it.

I decided my library would be a simple way to manipulate elements visually. At this point, I didn’t quite know how — but all you need is the kernel of the idea.

Step 2: Mock-up how would use the library

You always mock-up a webpage before you start building it right? Whether on paper, Photoshop, or even in code, it helps to pretend what the finished product will look like before you build it. It helps you to see obvious bugs, conflicts, and unwanted interactions you don’t catch when looking at the problem mentally.

Have you ever mocked-up your code?  Write some implementation, pretending that the class or object you are dealing with exists. Trust me, it will solve problems!

I want my library to do visual stuff with elements, and I like how jQuery looks. How about this?

Looking at my pretend implementation, I can see 1 problem and a hand-full of design implementation points.

The problem: $ as a function name is likely to conflict with lots of other libraries. Through some Googleing, I learn at StackOverflow that functions must start with a $ (dollar-sign) _ (underscore) or letters.

We can also tell some design patterns:

  • _ is the function name
  • _ must accept one or more parameters
  • _ should return itself so that a dot-operator will work
  • _ must control its scope so that we can have more than one _() on a page
  • dot-operator methods must also return the _ object for chaining

Step 3: Code up an outline

At this point, we know enough about the goal of our library, and how we will implement it, to begin outlining the structure of our library.

It may be useful for some (me) to review javascript function/object  prototyping.

Step 4: Fix-up the constructor

Now don’t try and run your code just yet: we have a pretty big scope issue (besides no functionality):

When our _() function returns this , it is actually returning the entire window, or the global scope.  Therefore, when we call _().toggle() , we are asking the browser to call the toggle() method which belongs to the window. Obviously this fails.

This problem can be solved by recursively creating another _ object using the new keyword.

What is the new keyword in JavaScript?


For an in-depth look at this problem, read more about JavaScript constructors

Next to implement in our constructor: making the _() represent an element with some bonus error prevention.

First, we create an about object that will be returned, if the implementation doesn’t specify an element id. Next, we check if the id parameter was sent, and then create a variable to contain that element.

Here is a final version of the _() constructor:


Step 5: Prototype method implementation

This step is pretty fun: being creative, and implementing what you want your library to actually do!

I mentioned earlier that I wanted my library to do some visual manipulation of elements. Make a list of what you want to do. I came up with the methods:

  • hide ()
  • show ()
  • bgcolor (color)
  • val (value)
  • toggle ()
  • size (height, width)

The depth of this step depends on the functionality of your library. Mine were rather trivial to implement:


Demo or download the finished library here

Part 2 – Event Handling

Final thoughts

Writing my own small library was a good way for me to learn about JavaScript. One of the great ways to learn more is to study the code of other libraries and see how they work.

Did you use this tutorial to create your own library? I would really like to hear about it. Please leave me a comment below.


Stack Overflow user W3Geek asked a question about part of this tutorial. Visit his question: How do these pieces of code function exactly? His question is focused on Step 4 about the object constructor. User Leland Richardson does an excellent job explaining this further — I’d direct you to his thorough explanation rather than duplicating it here.

Author: Michael Jasper

Michael is a Web Developer located in Northern Utah. When not programming, he enjoys spending time with his family, exploring the great-outdoors, and hit-and-miss cooking experiments.

  • Tim Reynolds

    A good read.

    Question: your show function sets the style to inherit. I believe it should be an empty string. By setting it to inherit, you would override the display of a class assigned to the element. I wrote up a gist that shows you what I mean.

  • Chris

    Hmm, just in case you haven’t heard, there’s a very popular library that also makes use of the _ global name, much like jQuery makes use of $: Underscore ( Nice article and happy coding!

  • I probably would have written all those functions outside the prototype so I can test them standalone (e is passed as param) and done some magic to bind them later on to bind them there.

    I probably wouldn’t have used prototype either to achieve chaining. Closures do just for fine for my purposes.

    There’s no single right way to write JS, though. It’s amazingly versatile little language. 🙂

    • admin

      Hey, Juho – Thanks for the feedback. I haven’t seen closures used to achieve chaining before. Mind demonstrating how you would do that (maybe or similar)? I agree, JS can be quite the utility-belt.

      • @admin

        For the jQuery like affect, this method is right. You really don’t need the prototype on that tho. You could have laid it out like:

        However, it might be worth noting how to do true JS chain, not a hack to use classes like C++:

      • Hi,

        I set up a simple demo for you. I just took your code and shifted it around bit. The biggest advantage of this approach is that it allows you to use both functional and chaining API.

        I’ll probably evolve this a bit further and write a blog post about it.

        I have written a chaining assert using a similar idea. It’s possible to maintain some state in the chain as you can see from this example (ie. the “not” op).

        If you ever get into Haskell, keep in mind that chaining is analogous to monads. They’ve just packaged it there a bit differently. By default Haskell code doesn’t have any order of execution. Chaining (monads) provide a way to execute things in order around there. In addition they’ll give you a nice way to control side effects.

        • Pretty clever actually passing around an identifier that way. I haven’t written any JS libs that way, but it’s worth checking performance.

          I asked this:

          and wrote this test there:

          I’m curious of the speed of your method? If you get time you should add a test to that with your example.

          • It’s effin slow. :S Here’s the modded test, .

            Slicing arguments makes it even worse. I wonder why it’s so snail-like. Is there anything that could be done about it?

            Anyhow it looks like prototypes are the way to go if one wants decent performance.

          • I figured out why it was so slow. I forgot to memoize it. 🙂

            Here’s the corrected version, . Here on Chrome it’s around seven times faster than the vanilla version. It seems to be faster than class based solution even.

            I think this is a good compromise. It gives me my dual API (both funcs + chaining) and decent performance.

      • Thanks for that! It’s just the answer I neeedd.

    • I probably wouldn’t have used prototype either to achieve chaining. Closures do just for fine for my purposes.

      Huh? Prototypes contain closures? You can’t even write JS without closures unless you are purely writing a single jQuery line or something.

      a.prototype.b = function(){
      var x = function(y){
      return this;

      That contains a closure, so what do you mean? Did you mean classes?

      Also, JavaScript is a prototypal language. Not using prototypal JS is like not using classes in C++.

      • Good point! That’s definitely a closure. Some confusion there on my part. I rarely use prototypes myself. I like to dabble with the functional side of JS these days.

        I probably should have rephrased that as “without prototypes”.

  • Nathan

    Probably the best way to deal with the identifier / identifier collision is to provide an override, as jQuery does with jQuery == $

    I think this is worthwhile because people are generally conditioned to using $ at this point.

    As mentioned above, Underscore does a lot of this, but it’s specifically built to not collide with jQuery from a functionality standpoint.

  • Weng

    Could you please provide example for the Visual Basic script please? VB Script is superior to the JavaScript and is made by a well known company. JavaScript is made by volunteers and charity workers.

    • admin

      Lol. Thank you for this great quote. I’ll be sure to give you credit when I post it around.


    • Dan

      Lol. Really? Wow.

    • Ralph

      LOL! This sarcastic comment really made my day! Or? Are you really serious?… Nah!

  • Pingback: My first JavaScript library – short.js « Matt Wein's Global Scope()

  • jeefo

    Thank you so much.
    That is actually what i was looking for it.

  • blackhat

    thanks man ,
    that really helped !

  • Chris

    Thanks a lot, this is exactly what I needed. I’m just starting to get familiar with java script for my new job, and this put me on the right track.

  • Jason

    Dude, thank you for such an informative, well-written post. It’s content like this that I really miss seeing on the web these days.
    Side note: I went to click the star button to rate the article, but it changed it to -1. So I tried clicking again to make it go up. Now it says -5. Sorry about that.

  • Billy Stanley

    The purpose of my own library is simply this: 1) I don’t want anything running on my sites that I didn’t write. 2) I don’t want to have to write anything more than once.

    • mdjasper

      Both lovely ideals! Did this article help you in writing your library?

      • Yes it did help both of us.

    • dude

      “I don’t want anything running on my sites that I didn’t write”

      haha ok have fun inventing the wheel 100 times more. How productive.

    • Andy Barrette

      People criticize me for reinventing the wheel also, but I usually find that when I do it I make a better wheel. People often ask me how I think of the stuff I do, about stuff that I came up with while reinventing the wheel. It’s clear to me from my experience that there’s still a lot of room for creativity.

  • weirdsteve

    Thanks so much, this is what i really wanted to learn about and with your help I have created an animation lib to make javascript slideshows and games more dynamic.. Thanks again!

    • mdjasper

      Thanks for your comments! Feedback like this motivates me to keep writing. BTW, I’d love a link to your library (if its public).

  • Excelent! I ll make my own.

    • mdjasper

      Good to hear this helped! What will your library do?

  • Search your Programming problems here

  • Ryanc1256

    Well this article helped a lot, with coding up my own js Library…
    Its Very Simular to Jquery…

    GitHub Link….

  • Rick Yoder

    Don’t know if you’ll answer this before I figure it out, but is there a way to access one function from the library in ANOTHER function of the library?

    My library (thanks for helping me make it), has a .css() method.

    _(“#testing”).css(“display”) would tell me the value of the display property of the element.

    I have another method, .getDimensions().

    I want to return the width and height of the element, using the .css() method.

    How can I do this (if possible)?

    • mdjasper

      Yes, you can call one function from your library from another function using the this keyword. Here is a simple example:

      var library = {
      add: function(a,b){
      return a+b;
      doubleIt: function(a){
      return this.add(a,a);
      library.doubleIt(3); // 6

  • Rick Yoder

    Never mind. Got it.

  • jenya

    can you please give the example how you using your library,i make something like this

    & its not changing anything
    can you contact me by gmail or facebook?

  • jenya

    & how i adding events
    thank you )))))))

  • jenya

    can you please give the example how you using your library,i make something like this

    & its not changing anything
    can you contact me by gmail or facebook?

    & how i adding events
    thank you )))))))

  • tvance929

    Something interesting to note… in VStudio I wasnt able to see the toggle function in the intellisense until after we changed the scope from window to the actual instantiation of the object. Makes perfect sense, just thought it was a cool sidenote.

  • Pingback: Convert Javascript functions into a library [on hold] | BlogoSfera()

  • Thiago Facchini

    Nice tutorial… but, what if I want events, such as onMouseOver or something similar?

  • Thiago Facchini

    Thanks for your post very useful.

    Btw: I’ve been looking for a template able to work with: parameters, events and methods.

    Anyone knows a good js template for this purpose? Thanks

  • Wow!

  • Pingback: JavaScript Module Pattern | BootStrapGo()

  • venz

    Thanks a lot for this article. It really helps me!!! I found now what i was looking for

  • Luiz Augusto

    Hey Michael. 🙂

    I’m using your tutorial to create my own lib and I’d like to know how would you do to create “private” functions (if you needed to)?

  • zhengjunwei

    very good!

  • CodySCarlson


    Great article! I’m familiar with creating modules, libraries, and frameworks — anything from simple functions to modules which include many design patterns. My biggest question now is, if I want to create a framework which contains several dependencies — how to manage this in an elegant way?

    My goal is to have a seamless inclusion of dependencies, but not make the user have to config a path or include the scripts themselves, for ease of use. In addition, I would like to conceal the dependencies to make marketing the framework less difficult (initially anyway).

    Right now I have the minified dependencies pasted into the source file (yuck), which is after approaching it with a document.createElement(‘script’) method. My first priority is to include RSVP.js as virtually everything will rely on Promises — however, I debate if I should first pull in RequireJS to make requests for all other dependencies, and to get the RequireJS config out of the way.

    Should I have a tightly-coupled source file containing the dependencies, where I have to past in newer releases of those dependencies???

    Should I package the dependencies and force the user to include them???

    How is this caveat typically solved?

    Any thoughts on how I can seamlessly load the dependencies and thoughts on approaches is very appreciated.

  • Pingback: DES225 Internship – Week 6 | Pat Harding()

  • Mike Morris

    You absolutely made me think about what I was doing and how I was blurring the lines between the logic part and the visual part. Angular was too rigid and knockout could not use my lovely TypeLite generated model interfaces directly and drag and drop project management with type safe drop zones and a load of drop placement templates has no business being in the same file as the ajax wrappers.

    That is how my frameworks begin. I think it is like throwing gold in the misc. stack to not record everything you know about programming into namespaced modular frameworks for the languages you use. My classes across PHP and C# include, among hundreds of business specific classes, 2 trivial classes that save me tons of time UspsAddress and GenericDescription. My grail is db table to view with no cast or convert along the way and back. In order to get there everything I learn including the scope matters as it is just beginning to matter to me in the way you are addressing it. My js is scoped to the application first then reaches out to set my event handlers on the document since all html5 DnD events bubble. The reason I did it this way is to avoid the conflict with jq and scope my application object to something like a Bootstrap container wrapping the panel or whatever wrapper..

    You definitely got my wheels turning this day!

  • M. Paul Peloquin

    Thanks for the info. You are awesome. I am using javascript for a

    project. I am comfortable in objective C and swift. I was using jQuery but way to large for what I need to do. You have provided a great solution.

  • Jhon Ronell Arana

    What does the e. ( this.e.) stands for?
    Sorry Noob

  • Dark Shadow

    So, where did the ‘e’ come from in = ‘none’ ? I thought it was just

  • Dark Shadow

    So, where did the ‘e’ come from in = ‘none’ ? I thought it was just

  • Mark Bauermeister

    I know I’m somewhat late to the party, but would you know the proper way to add namespaces to your library framework?
    Basically, I’m attempting to create something like “junior.UI.rainbowBG();” or “junior.App.restart();, junior being the name of my library.

    Furthermore, how should I handle functions that don’t require a target id? A call to my restart function (I’m running the code inside a runtime environment, not just a mere browser. So that function actually restarts the application it’s called from) would currently look like this: “_(‘ ‘).restart();”. Obviously, this isn’t the most elegant looking solution.

  • tarak M

    Hi mdjasper you article is superb.
    I have to create one visualization javascript file on top of d3.
    Plz be give the suggestions.

  • HongJinBom

    Thank you

  • Curlz

    The purpose of my creating a custom library is i have few files and using them want to create a library and use in other applications. can you guide me how to do that and how it will be helpful ?

  • Berk Derek

    Thanks that really helped