3

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?

Jack Bashford
  • 38,499
  • 10
  • 36
  • 67
Marcus
  • 45
  • 7
  • `$` is a function which creates a jQuery object - typically from a CSS selector or a DOM element, but also as here from a string of HTML. This line simply declares a variable `$newTweet` and assigns it that jQuery object as a value. – Robin Zigmond Mar 30 '19 at 08:35

2 Answers2

5

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.

VLAZ
  • 18,437
  • 8
  • 35
  • 54
4

OK, here's the breakdown:

A dollar sign precedes the value because it's a function - it's the jQuery function. ($())

It precedes the variable value because it needs to - the variable value is set to the return value of the function - in this case, the new element created.

The inside of the jQuery $ function is in quotes because if it was not, it would be assumed it's referring to a variable called <div class=tweet></div> - aside from being an invalid variable name, it doesn't exist, so this would throw an error. This is why the string is used.

Here is what the element actually looks like, as well:

var $newTweet = $("<div class=tweet></div>");
console.log($newTweet[0]);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

(The [0] above is only used to show the plain element - otherwise there's heaps of additional stuff).

Jack Bashford
  • 38,499
  • 10
  • 36
  • 67