Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare variables in jQuery

I'm working on a project for school, I saw some example solutions online and I can make sense of most of the code but I'm not entirely sure what this line does.

var $newTweet = $('<div class=tweet></div>');

I'm assuming that it creates a jQuery variable with the value set to a blank <div> with the class of tweet, but I want to be certain and also understand the syntax.

Why does a dollar sign precede the variable value? I know dollar signs are used in jQuery and understand why one precedes newTweet (the variable name) but I don't understand why it precedes the variable value.

Also why is the inside of the $() in quotes?

like image 474
Marcus Avatar asked Dec 12 '25 01:12

Marcus


1 Answers

The $ character is a shorthand for using jQuery, so $('<div class=tweet></div>'); invokes the jQuery library to create a new HTML element and put it into a jQuery wrapper, so you can interact with it in an easy way.

On the other hand var $newTweet is not actually special, from language perspective: $ is a valid character to have in a variable name. However, it is a common way to tell other programmers that the variable holds a jQuery object, so they can interact with it using the jQuery API. It's a variation of Hungarian Notation where you put the type the variable hold in the name of the variable.

like image 89
VLAZ Avatar answered Dec 14 '25 13:12

VLAZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!