What is the difference between Javascript and jQuery?

17

I think of Jquery as a Framework Javascript in order to optimize writing, Ajax is a good example.

  • In addition to facilitating writing, is there a difference between the two?
  • What are the advantages and disadvantages of using jQuery?
asked by anonymous 26.04.2017 / 20:28

2 answers

26

jQuery is JavaScript. In other words, jQuery is a library written / constructed with the JavaScript language.

There are two main reasons for having a library like jQuery:

  • Can simplify life to the programmer, with fewer lines of code to do things than in native JavaScript would need more lines
  • have an API that is the same in all browsers that this library supports

Thinking about the jQuery library as a tool to make life easier for the programmer, the idea is to save work, in the extension of code needed to write and minimize possible errors.

For example an ajax call to fetch a JSON would look like this in jQuery:

$.getJSON('/o/meu/url', function(data) {

});

To do the same in native JavaScript you would need more rows:

var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // tudo correu bem!
    var data = JSON.parse(request.responseText);
    // aqui é o mesmo que o interior do exemplo com jQuery
  } else {
    // este pedaço é corrido se houver algum erro

  }
};

request.onerror = function() {
  // este pedaço é corrido se houver algum erro
};

request.send();

In practice jQuery has these lines all written in your library (in the JavaScript file that we have to load with the page) but it shows the programmer only the methods that build and simplify things as I showed in the first example.

jQuery is not always necessary, in fact it is not as important as it once was. An interesting site with common features that do well in native JavaScript nowadays: link

When we program an application, and users use our program in different browsers, we run the risk that the JavaScript we write will not work in some browsers. This is because each one implements things with slight differences, or because some are more modern than others. The role of libraries such as jQuery is to create an abstraction layer to only use its API, not native JavaScript. Thus, within the library, the necessary corrections and adjustments are made to a jQuery code as $(document).on('click', ... to be decomposed into JavaScript that a given browser understands and provide the same functionality.

A classic example is the way to tie event headphones in older versions of Internet Explorer.

The modern way is elemento.addEventListener but IE was elemento.attachEvent . To avoid writing a date code like this ( source ):

//addEventListener polyfill 1.0 / Eirik Backer / MIT Licence
(function(win, doc){
	if(win.addEventListener)return;		//No need to polyfill

	function docHijack(p){var old = doc[p];doc[p] = function(v){return addListen(old(v))}}
	function addEvent(on, fn, self){
		return (self = this).attachEvent('on' + on, function(e){
			var e = e || win.event;
			e.preventDefault  = e.preventDefault  || function(){e.returnValue = false}
			e.stopPropagation = e.stopPropagation || function(){e.cancelBubble = true}
			fn.call(self, e);
		});
	}
	function addListen(obj, i){
		if(i = obj.length)while(i--)obj[i].addEventListener = addEvent;
		else obj.addEventListener = addEvent;
		return obj;
	}

	addListen([doc, win]);
	if('Element' in win)win.Element.prototype.addEventListener = addEvent;			//IE8
	else{		//IE < 8
		doc.attachEvent('onreadystatechange', function(){addListen(doc.all)});		//Make sure we also init at domReady
		docHijack('getElementsByTagName');
		docHijack('getElementById');
		docHijack('createElement');
		addListen(doc.all);	
	}
})(window, document);

We use jQuery, which has more or less this inside your file .js and we use its abstraction layer (API) that is only:

$(elemento).on('nome-do-evento', ...

More information:

26.04.2017 / 20:40
18

JavaScript is a language, while jQuery is a library focused on manipulating DOM elements. Libraries are made based on a language and frameworks are usually made based on a library.

What happens is that javascript is an old language and development with it is a bit hard work and sometimes it is necessary to write a lot of code. Then jQuery is a framework, that is, it is javascript itself redefined in a more modern way, simple to use and using less code.

One difference that should be highlighted is that JavaScript runs natively in browsers whereas for jQuery a reference to your library must be added in HTML.For example:

<script type='text/javascript' src='//code.jquery.com/jquery-1.10.1.js'></script>

Advantages of using jQuery:

  • Direct access to any component of the DOM, that is, there is no need several lines of code to access certain points in the DOM.

  • The use of style rules is not subject to any limitations due to browser inconsistencies. Even CSS3 selectors can be used without any restriction.

  • Manipulation of content, without limitations, with a few lines of code. Support for the full range of interaction events with the without limitations imposed by browsers.

  • Possibility to insert a wide variety of animation effects with a simple line of code.

  • Simplified and unrestricted use with AJAX and programming, such as PHP and ASP.

  • Simplifying scripting.

  • Cross-browser job.

  • It is possible to select elements with greater ease, greater compatibility, and with less code. Here's an example of a code in JavaScript and the same in jQuery :

    - In JavaScript:

var botao = document.getElementById("botao");

if (botao.attachEvent) {
    botao.attachEvent("onclick", function(event) {
        alert("Você clicou no botão, usuário do IE!");
    });
} else if (botao.addEventListener) {
    botao.addEventListener("click", function(event) {
        alert("Você clicou no cabeçalho!")
    }, false);
}
<button type="button" id='botao'>Clique</button>

- In jQuery:

$("#botao").click(function (event) {
  alert("Você clicou no botao!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttontype="button" id='botao'>Clique</button>

Note how the jQuery syntax is much smaller.

Disadvantages of using jQuery

  • jQuery has performance loss. This type of loss is inherent in any abstractions, but is accentuated by the amount of extra features involved.

    The implementation itself is also less optimized when compared to
    implementations that already comes from the core of Javascript itself. It is good to avoid using jQuery at least in very long loops or nested where a performance penalty can multiply or even grow exponentially.

  • jQuery is a library, so it has other competitors. If you you are using a framework such as the Angular that has its own jqLite, there will be no need to use jQuery. Know JavaScript, however, it will always be useful.

References:

26.04.2017 / 21:13