jQuery vs Vanilla Javascript

Before Javascript was created, websites were all pretty much static. When Javascript was introduced, it changed how websites were being created starting from their appearance to their functionality.

All of a sudden you could submit a form without refreshing the page, add animations and also manipuplate DOM elements whenever it's needed.

Soon enough something else was introduced: jQuery.

jQuery is a library of Javascript functions and utilities built by developers from all around the world to simplify development for developers. jQuery can be used to trigger CSS animations, manupilate DOM elements, inject DOM elements, post and get Ajax requests to an endpoint and much more.

The fact that jQuery is also cross browser compatible is also a great advantage, reducing the time developing multi browser functions and testing each one to make sure they work.

A Comparison

When compared, the code of jQuery is shorter than Vanilla Javascript. The example below will demonstrate how to detect a click on a button and trigger an alert in both jQuery and Vanilla Javascript.

jQuery

$('#firstButton').click(function() {
    alert("TheFrontender");
});

Vanilla Javascript

document.getElementById("firstButton")
.addEventListener('click', function() { 
    alert("TheFrontender");
});

Another example - Ajax Request:

jQuery

$.ajax('/jquery/getjsondata', { 
    dataType: 'json', 
    success: function (data,status,xhr) { 
        console.log(data); 
    }, 
    error: function (jqXhr, textStatus, errorMessage) { 
        console.log(errorMessage); 
    }
});

Vanilla Javascript

fetch('/js/getjsondata, {
    method: "GET",
    headers: {
        "Content-type": "application/json;charset=UTF-8"
    }
}).then(function (response) {
    if (response.status == 200) {
        return response.data.json();
    }
}).catch(function (error) {
    console.log(error);
});

Though just because its simpler using jQuery, doesn't mean it doesn't come with a few disadvantages. Being a library, it contains a lot of different utilities, some of which won't be used at all or won't be needed for certain projects which could be cumbersome for some projects and affect their agility and speed.

Verdict

Lately as seen on the internet, a lot of developers are moving away from libraries like jQuery and instead focusing on writing efficient and elegant Vanilla Javascript code that will be faster.

There isn't really a good time to use jQuery over Vanilla Javascript or vice versa. It's up to the developer's discretion to go with the one they feel will be the most efficient. Developer's experience also plays a role, as developing solely with jQuery can limit the learning of complex Vanilla Javascript tools and functions which could add to an increase in development time or causes the code to not be as efficient as it could be.