Codementor Events

JavaScript vs jQuery: Which One Should You Use?

Published Oct 16, 2021
JavaScript vs jQuery: Which One Should You Use?

A web developer at some point of time, always asks this question to himself, "What should I code in: jQuery or JavaScript?"

A few beginner web developers want to know the exact difference between the two.

Actually, JavaScript and jQuery are not two separate programming languages. Instead, they have the same JavaScript code underneath. The real difference lies in the way a developer uses them while coding. jQuery is a JavaScript library designed for DOM (document object model) operations in HTML page. For example, animation, event handling, traversing, AJAX interactions, and more.

A strong hold on JavaScript is necessary to use either of the two scripting languages. Therefore, in case you have just started out, please get a basic understanding of JavaScript. Then you will find jQuery does the same thing JavaScript does, but requires fewer lines of code than what traditional JavaScript requires.

We can now do a comparison study of both these scripting language and suggest which one to use for your next web development project.

JavaScript

JavaScript is a scripting language used to make web pages more dynamic and have increased user interactions.

JavaScript is used in most websites and apps, most popular being Gmail and Facebook. The dynamic nature of websites which changes a section of the page without reloading the entire page is accomplished by JavaScript.

Another cool example of what JavaScript can do is detecting whether the visitor of a website is opening the link from a computer or a mobile phone. We can then render the mobile version of the website if the visitor is using a mobile browser.

JavaScript has endless use cases where it has changed the way people interact with websites. Also, it is not limited to just building websites, JavaScript is very actively used for server side development (example: Node.js), desktop applications, developing dynamic games, etc.

There was a time few years back when JavaScript was rendered differently by different web browsers, so it was a pain for web developers to code in JavaScript and make it work similarly across all popular browsers.

This has changed, as new standards by W3C now force all web browsers to implement JavaScript uniformly. This makes developers' lives easier as they no longer have to waste time debugging some code to make it work for on particular web browser.

jQuery

jQuery is a fast, small, and feature-rich JavaScript library. It handles all cross-browser issues itself.

Doing HTML DOM traversal, manipulation, animation, event handling, and Ajax has become very simple using jQuery. Also, jQuery also makes the same code work uniformly across all web browsers. "Write less, do more" is the motto of jQuery.

JQuery is very simple to grasp and even easier to use, therefore its learning curve is very shallow. There are other JavaScript-based libraries such as MooTools, but jQuery is the most popular because it is so easy to use and extremely powerful.

JQuery has been created to perform most common scripting functions while using very few lines of code. Therefore, what takes 10 lines using vanilla JavaScript can be done within 2 lines using jQuery just by calling the relevant jQuery function.

Code Example 1

Let’s look at a basic ‘mouse click event’ example:

Suppose we have an input element for a button and we want to listen to the mouse click event on this button, and get notified by an alert box message.

<input id="mybutton" type="button" value="clickMe"/> 

Here is how one would do it with JavaScript:

document.getElemementById("mybutton").addEventListener('click', 
     function(){ 
          alert("Hey, You clicked me ?");
     }
);

The same thing can be done in jQuery using the following line of code.

$('#mybutton').click(function(){
      alert("Hey, You clicked me ?");
});

Code Example 2

Let's create a simple web app that will send a request to the server to obtain the current date and time. We'll be using AJAX, or Asynchronous JavaScript and XML. AJAX is basically a collection of web development techniques used on the client-side to create asynchronous web apps. XMLHttpRequest (XHR) is a JavaScript Object used to send HTTP requests to a web server, and then loads the server response back into the script. This response can then be processed by the client (the browser).

So, after briefly explaining some concepts, let's look at what the app would look like.

JavaScript Output

This sample app has a button which, when clicked upon, initiates a request to the server. The server then calculates the current date and time before it sends it back to the client as a response. Then, the response is added to an already defined div tag, which displays the date and time.

<div id="resultarea"></div>

In the screenshot above, the date and time is set in the “Asia/Calcutta” time zone as defined in the server-side script saved with name getDateTimeServerScript.php, and it returns the current date and time.

<?php
       date_default_timezone_set("Asia/Calcutta");
       echo date('Y-m-d H:i:s');
?>

At any rate, both the jQuery and JavaScript version looks identical on the browser, and the difference lies in the internal implementation of the code. Let's take a look then!

JavaScript Version:

This is the JavaScript Version of the webpage ( JavaScript.html ):

<!DOCTYPE html>
<html>
<head>
<script>
function loadCurrentDateTime() {
  var xhttp = new XMLHttpRequest();
   
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("resultarea").innerHTML = xhttp.responseText;
    }
  }
  xhttp.open("GET", "getDateTimeServerScript.php", true);
   xhttp.send( );
}
</script>
</head>

<body>

<button type="button" onclick="loadCurrentDateTime()">Load Current Date Time</button>
<div id="resultarea"></div>

</body>
</html>

JQuery Version:

This is the jQuery version of the same webpage (JQuery.html).

<!DOCTYPE html>
<html>
<head>

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

<script>
function loadCurrentDateTime() {
  $.ajax({
    type: "GET",
    url: "getDateTimeServerScript.php", 
    cache: false,
    success: function(data){
     $("#resultarea").text(data);
    }
  });
}
</script>

</head>
<body>

<button type="button" onclick="loadCurrentDateTime()">Load Current Date Time</button>
<div id="resultarea"></div>

</body>
</html>

Anyhow, both the JavaScript and jQuery codes above do the same thing, but JavaScript does it by creating an XMLHttpRequest object and then processing the request by sending it to server. Then, it displays the response back in the “resultarea” div.

Alternatively, jQuery does the same thing by using the jQuery library, which was included into the code using the line
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

This library offers various pre-built functions for AJAX - one of them being $.ajax. The parameters of the request were passed, and the response was collected in its callback function success.

What’s best for my project (which approach to use)?

The most important point to consider before jumping to a conclusion of which approach you should use is that, since both JavaScript and jQuery are internally the same, either can be used to recreate the same effect as done by other’s code.

Therefore, there is no point in spending a whole lot of time evaluating whether JavaScript or jQuery is appropriate for a particular project or task.

However, if one has to choose between the two, jQuery is usually more than sufficient for most web-based applications and projects, and therefore, jQuery holds the winning flag as it can do the same task in lesser number of lines of code as compared to core JavaScript code.

If you are a novice developer, you should actually spend most of your time grasping all the concepts of JavaScript and building a few projects using core JavaScript. In other words, beginners should refrain from using jQuery initially. It is really useful to first understand how JavaScript interacts with the structure of an HTML page and how it can work in different possible scenarios.

Conclusion

jQuery makes things so simple and precise that it save time and speeds up the development time and lets developer focus more on implementing the business logic that the project is supposed to do. However, it is advisable to study both deeply and thoroughly and decide yourself which one to use depending on the given scenario.

Discover and read more posts from Ashish
get started
post comments1Reply
Ferran Buireu
3 years ago

I appreciate the article despite I disagree with (some of) your conclusions; it’s true that jQuery can save you a few lines of code rather than JavaScript, however, and especially for beginners, it’s far way more important to learn the fundamentals of JavaScript rather than a framework/library (and quite old-fashioned like jQuery). This will ensure that you can move from one library to another without paying the technical debt. All front-end libraries work with JS/TS.

Moreover (and for me the most important point), jQuery points and manipulates directly the DOM, which has a HUGE impact on performance because of the cost for the browser to perform “live” actions on the real DOM. On the other hand, learning JavaScript allows you to learn the basics for React, Vue, Angular or Svelte (and many others), which are the cutting-edge frameworks that manipulate the virtual DOM (vDOM) in order to create boosting website without debt penalty.

I agree with you that each case needs to be separately studied, however, in 2021, I’d say that using jQuery should be 10% of the use-cases.

Sometimes less is not more.

Thanks for the article anyway :)