Over a million developers have joined DZone.

Chaining Functions in JavaScript

· Java Zone

Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience, brought to you in partnership with JetBrains

Most of us are aware of the all-famous Jquery dem:


It is a gem of an example of chaining functions.

There are many resources out there that demonstrate various ways of chaining javascript functions, but, I always like to explore my own ways of doing things. Let people call it re-inventing the wheel, but I'd like to make my own wheel! [ Enough of Nehilisim!]

Below is a simple code that I managed to pull, which is closest to the Jquery demo and, as always, might be done in better ways. (You are welcome to let me know of any better way in the comments section or via e-mail.)

$ = (function (document) {
    var self = '';
    return {
        get: function (selector) {
            self = document.querySelector(selector);
            return this;
        addClass: function (new_class) {
            return this;
        show: function () {
            self.style.display == 'none' ? self.style.display = 'block' : 
            return this;
        hide: function () {
            self.style.display !== 'none' ? self.style.display = 'none' : 
            return this;
        toggle: function () {
            self.style.display == 'block' ? self.style.display = 'none' : 
            self.style.display = 'block';
            return this;

With this one can do something like: 


Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.


Published at DZone with permission of Hemanth HM, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}