Can anyone explain to me the meaning of the $ dollar symbol in Javascript?

Asked

Viewed 487 times

2

The codes in question are as follows::

var $item = $(this).parent().parent().find('input');

what use is this $ in the first code, if I remove it what difference will make?

function doHomework(subject) {
  alert(`Starting my ${subject} homework.`);
}

to which the $ is referring in this case? what needs to be defined as Subject so that it makes sense to use it?

2 answers

4


var $item = $(this).parent().parent().find('input');

This is a code in jQuery. $ is a valid variable name, and the jQuery library by default defines a variable with the name $ as an alias for jQuery, in other words, $(this) is just a shorter way of writing jQuery(this)

On the other hand, in $item, the dollar sign serves only as an indicator, to make it clear that that variable is storing an object returned by jQuery. If you remove the cipher from this variable, the code would work the same way.

`Starting my ${subject} homework.`

Already in this line of code the cirão has a totally different meaning. Strings bounded with tics can embed variables that are defined within the markup ${}, in other words

`Starting my ${subject} homework.`

It’s just an alternative way of writing

"Starting my " + subject + " homework."

If you remove the dollar sign from this string, the variable subject would not be embedded in that string, and instead of generating a string like Starting my arithmetic homework. for example, you would simply generate Starting my {subject} homework.

3

There are 3 different cases there!

$(this).parent().parent().find('input');

In this case $ is simply a variable name. There is no special meaning!

When you include the library jquery in the context of your page (adding your tag to HTML), this library exposes its features by defining the global variables jQuery and $. Literally somewhere in jquery code will be written $ = { ... }.

var $item

This is more of a good practice convention. When a variable has a "jquery object", it is a convention to name with $ before. This is present in famous style guides like the Airbnb style guide

alert(`Starting my ${subject} homework.`);
// é o mesmo que
alert("Starting my " + subject + " homework.");

This one is actually a special javascript syntax called literal template. When you define a string with inverse quotes ` instead of single quotes or double quotes, when using ${} it will interpolar a variable inside that string. It’s like a <?= > PHP, only for JS.

Browser other questions tagged

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