What is the difference between Javascript and jQuery?

Asked

Viewed 7,627 times

23

Think about the Jquery as a Framework JavaScript in order to optimize writing, the Ajax is a good example.

  • In addition to easier writing, there is a difference between the two?
  • What are the advantages and disadvantages of using jQuery?
  • 1

    Related: https://answall.com/questions/17501/qual-%C3%A9-a-difference%C3%A7a-de-api-library-e-framework

  • 1

    Javascript vs jQuery - Everything You Need to Know http://scheduler.co/jquery-vs-javascript-tudo-que-voce-youneed to know/

  • 6

    Related: https://i.stack.Imgur.com/Bzawb.gif

  • If you’re not going to make a great framework, or complex system, or giant website, consider using pure Javascript.

  • @Leocaracciolo I really liked the file you posted here in the comment. Posted this doubt, because some people questioned me on the subject and that’s what I knew so far about.

  • 1

    otimizar a escrita Not always.....

  • the answer was accepted very quickly.

  • @Marceloboni has some case where the Javascript is simpler?

  • @Marconi, at least a good example

  • @Marceloboni I saw in Sergio’s reply this same link. innerHTML by the way is the one I most use.

Show 5 more comments

2 answers

32


jQuery is Javascript.
jQuery is a written/built library with the Javascript language.

There are two main reasons to have a library like jQuery:

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

Thinking of the jQuery library as a tool to make life easier for the programmer, the idea is to save work, in 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 it would take more lines:

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 all these lines written in its library (in the Javascript file we have to load with the page) but shows the programmer only the methods that build and simplify things as I showed in the first example.

jQuery isn’t always needed, it’s not as important as it once was. An interesting site with common features that are done well in native Javascript nowadays: http://youmightnotneedjquery.com/

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

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

The modern way is elemento.addEventListener but IE had elemento.attachEvent. To avoid writing a code date 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 that inside your file .js and use its abstraction layer (API) which is only:

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

More information:

  • I liked the example of addEventListener. I thought the way that browsers companies write their js followed a pattern. So I can say that jQuery is more than necessary?

  • @Marconi yes, exact. jQuery or another library is important if you need to use a lot js in different browsers.

26

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

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

One difference that should be highlighted is that the JavaScript runs natively in browsers while for the jQuery a reference should be added to your library 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, i.e., there is no need for multiple lines of code to access certain points in the DOM.

  • The use of style rules does not suffer any kind of limitation due browser inconsistencies. Even CSS3 selectors can be used without any restriction.

  • Content manipulation, without limitations, with a few lines code. Support for the full range of interaction events with the user 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.

  • Simplification in the creation of scripts.

  • Cross-browser job.

  • You can select elements more easily, more easily compatibility, and with less code. See an example of a code in JavaScript and the same in jQuery:

    - 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>
<button type="button" id='botao'>Clique</button>

Note how much smaller jQuery syntax is.

Disadvantages when using jQuery

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

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

  • jQuery is a library, so it has other competitors. If you is using a framework like Angular that has its own jqLite, there will be no need to use jQuery. Javascript knowing, however, it will always be useful.

References:

  • 7

    Good answer, +1

  • 5
  • 4

    @jbueno I am new in programming and the question caught my attention, and as I did not know the subject resolve to research on and put here the answer to help future people who may have come to have this same doubt. As you noticed I did not settle for just one source and researched on a second to elaborate more clearly the answer. I recognize my failure of n to have put references, but how you tbm can constadar ja correct this.

  • 3

    @Alíciatairini Excellent answer for a newbie. I hope you answer more and more questions with this quality :)

  • 2

    @You don’t have to explain yourself to me, I just put the references.

  • 5

    Aliciatairini: as I mentioned above I found the good answer. Reading with more emphasis, and as others noticed, I see that the content is not yours. The answer as it stands is plagiarism from other articles. I didn’t actually find a phrase in the answer that was yours. @Marconi edited and changed variable names (I don’t quite understand why) but even the code is copied. This is not ok.

  • 6

    What is good is that you went to the trouble of searching and (probably) read these articles. Then it would be interesting to write something of yours, with the knowledge that you read there. As this can not stay. I leave a comment to know what I think. I’ll think about it more, which has already been discussed at the goal. Otherwise I love to see new programmers like you participate in the site, and I hope that you continue with answers of this level, that they are yours.

  • 1

    @Sergio I just left as executable code.

  • @Marconi what I didn’t understand was why was changing the variables of cabecalho for botao.

  • 1

    @Sergio is because it had events of click and it was supposed to make more sense!

  • 1

    @Marconi ok. Good to have been executable, that was good.

  • 3

    @Sergio Criticisms are always welcome. In my next answer I will do my best to put with my own words!

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.