Discover Why Vanilla JavaScript is the Future of the Web

WordPress

Do you want to drive more traffic to your web? So do I! That's why we created Nelio Content, a new plugin that automates content promotion in social networks. Want to know more?

Raise your hand if you’ve ever used libraries like jQuery or Underscore.js¬†ūüôč. Don’t be shy, this is a safe space¬†ūüėá… Besides, I know you’ve used them. Why wouldn’t you? All the utilities they include make our lives easier and they’re already included in WordPress Core, right? But think about the following question: does it make sense to use a library just because you can? Shouldn’t you be more mindful of what you use and why?

Today I’d like to briefly talk about these libraries and the problems they try to solve. Then, we’ll discuss how most of these problems can be easily solved using vanilla JavaScript‚ÄĒa faster and lightweight alternative.

JavaScript Libraries

The goal¬†of a library is to abstract¬†a set of more or less complex operations and build an API¬†with convenient, easy-to-use functions. For instance, with¬†jQuery¬†you can perform operations like manipulating the DOM, managing events, creating animations, and so on. To do this, jQuery exposes a clear and concise API that’s compatible with all major browsers.

jQuery Logo
jQuery’s Logo says it all: “write less, do more”. I think this perfectly summarizes the goal of any library ūüėČ

Libraries are toolsets for developers‚ÄĒthey help us be more efficient. In fact, you’ll find the perfect summary of what a library is in jQuery’s logo: “write less, do more”. That’s the goal: to make easy what, by definition, isn’t.

jQuery

jQuery was first launched in 2006 as a cross-platform JavaScript library designed to ‚ÄĒ¬†surprise! ‚ÄĒ simplify the client-side scripting of HTML. Its syntax¬†was designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. Moreover, the library can be easily extended using plugins. One of its most well-known extensions is¬†jQuery UI, “a curated set of user interface interactions, effects, widgets, and themes.”

Screenshot of Nelio Content's Dialog for Adding new Social Messages
Screenshot of Nelio Content‘s Dialog for adding new social messages, created using the dialog module in jQuery UI.

If you don’t already know this library (really?), Wikipedia’s article¬†has a pretty good overview of its features and history. Then, you can move to the¬†official docs or any¬†online tutorial¬†to learn the basics and get the most out of it.

Underscore.js

Another common library (but not as famous as jQuery) is Underscore.js, which includes several utility functions. Some common examples are the functions map (to convert one array in another by mapping each element into something different), filter (to filter the elements that satisfy a certain condition), or pluck (to convert an array of objects into an array of values extracted from a property of said objects), among many, many others.

One of the reasons for Underscore.js being “so” popular is its relationship with the MVC framework Backbone. Backbone offers all the required tools to create data models and views, and bind everything with its own event system. If you don’t know this framework, maybe you’ve heard of React, Angular, or Vue, all of which are Backbone alternatives. From our perspective, the main difference is the fact that Backbone and Underscore.js are included in WordPress Core.

The Downside

So, if libraries are so great, if they ease our jobs that much… why wouldn’t we use them? Well, the main problem with libraries like jQuery, Underscore.js, or Backbone is their weight.¬†For instance, jQuery is about¬†250kb (90kb if minified). Not that bad, huh? But, if you have 50,000 monthly visitors, jQuery will consume 4Gb!¬†So I think you should ask yourself the following question: do I really need this library? Or am I using it only because I already know the technology?

SpongeBob weight lifting
You may think they are’t, but jQuery and other JavaScript libraries are pretty big.

I used to use jQuery everywhere. It didn’t matter how easy or complex the problem I was trying to solve was‚ÄĒusing jQuery was just… convenient. For instance, if I wanted to change some text in my page, I’d load jQuery to retrieve the element and edit it easily ($('.element').text('text')). Of course, this was a poor decision.

The Solution to All Your Problems‚ÄĒVanilla JavaScript

Well, not all your problems, probably‚ÄĒbut many! JavaScript has changed and evolved a lot during the past few years, and today we can do most of the things these JS libraries helped us to do… without loading these libraries at all! So, without further ado, let’s take a look at¬†6 examples of all the things you can do with vanilla JavaScript.

1. Selecting DOM elements with Vanilla JavaScript

I’d say most of us use jQuery for this feature‚ÄĒselecting DOM elements. jQuery has a short an efficient syntax for doing so, but vanilla JavaScript is quite elegant too:

Sure, it’s slightly more verbose… but it’s not 90kb long, isn’t it? Moreover, using native operations is always faster than relying on a third-party library.

Now, I know what you’re thinking: the problem with vanilla JavaScript is not its lenght, but the fact that we completely changed element selection‚ÄĒin jQuery we could use CSS, whereas in vanilla JS we have specific functions for selecting elements by ID, class, or node type. Well, you’re right, but you can also select elements using CSS expressions in Vanilla JavaScript:

2. Traversing the DOM

Another common operation when working with the DOM is traversing the DOM tree‚ÄĒmoving from one element to the other, from child to parent, and so on. All these operations exist in vanilla JavaScript, rendering jQuery unnecessary:

3. Setting and Getting Attributes

Once we have an element, we’ll probably want to change it somehow or get a certain property. Well, this is quite easy in both jQuery and vanilla JavaScript:

4. Operating with Multiple Nodes from the DOM

One of the great features included in jQuery is command chains. For instance, you can select a set of elements and apply an operation (like adding a class) to the whole collection:

Unfortunately, you can’t do that using vanilla JavaScript. If you want to apply an operation to all elements included in a collection, you’ll have to iterate through them all using a loop construct:

That’s what jQuery does internally, of course. But, again, its syntax is so convenient that makes things easier and faster. But, full disclosure, iterating through arrays in ECMAScript 6 (the new version of the JavaScript language) is quite easy and elegant too. I’ll show you a few examples in the next section¬†ūüėČ

5. Working with Arrays

We already mentioned some of the utilities included in Underscore.js for working with arrays. Well, almost all of them have their counterpart in vanilla JavaScript:

As you can see, the syntax and function names are very similar, so why would you use one over the other? JavaScript functions are slightly faster (Underscore.js will use the vanilla JavaScript functions when available) and they are part of a standard, whereas third-party libraries can differ one from the other (slightly different function names or parameter order), making it more difficult for you to understand a code that uses a library you’re not familiar with.

Finally, if you were wondering how we can use ECMAScript 6 functions and syntax to implement the chained command we saw in the previous section, here you have it:

Essentially, we select multiple elements using querySelectorAll and apply a lambda function to all the elements in the result using the forEach operator. As you can see, lambda functions in ECMAScript 6 got rid of all the syntax sugar and can be expressed more succinctly. Cool, huh?

6. Working with Objects

Finally, I’m sure you’ll find yourself working with objects often‚ÄĒoperations like getting all the attributes of an object, extracting their values, and so on are very common. Underscore.js and vanilla JavaScript are quite good at them:

One of my favorite functions included in Underscore.js for working with arrays of objects is¬†pluck. This function extracts the value of a certain property from all the elements included in the array, creating a new array. If you compare the Underscore.js function and its vanilla JS counterpart (again, using ECMAScript 6), you’ll see that both alternatives take exactly the same number of characters, which is pretty cool:

Wrapping Up

There’s a lot of things we can do today using vanilla JavaScript, rendering third-party libraries unnecessary. Stop using these libraries blindly and think if they’re really necessary for your project. If they are, include them by all means. But if they aren’t, try to use vanilla JS and get used to the future of the web!

Featured Image by Ilya Ilyukhin via Unsplash.

PoorMehGoodVery GoodAwesome! (4 votes, average: 4.00 out of 5)
Loading...

by

He obtained his PhD in Computer Science at UPC. David leads the analysis and design of our services and the user support area. He's interested in a variety of areas, including conceptual modeling, virtual reality, and 3D digital printing. He contributes to the WordPress community by participating in meetups, seminars, and the WCEU.

Leave a Reply

Your email address will not be published. Required fields are marked *