Code Farmer Code Farmer - 2 months ago 6x
Node.js Question

$ sign in javascript is trying to kill me, who can get me out of it

I am new to nodejs, I known $ is used in jQuery, but the tutorial I'm learning shows me the following piece of code, which confused me by it's '$',

var $ = cheerio.load(res.text);
$('#topic_list .topic_title').each(function (idx, element) {
var $element = $(element);
var href = url.resolve(cnodeUrl, $element.attr('href'));

can anyone try to explain the 5 $s here? Thank you in advance.


The same way that you can have a variable named a, you can have a variable named $ or _. searching google on variable names in javascript will provide more info, but to the point of your question, consider this:

var a = 1; //creates a variable named a, value is one
var $ = 1; //creates a variable named $, value is one

because it is javascript, a variable can also hold a function:

var a = function(){return 1;}  // calling a() will return one
var $ = function(){return 1;}  // $ is a var whose value is a function.

Now, when you have a function that you call very frequently, forexample JQuery library has a function called JQuery() which wraps elements and contains everything else, it makes sense to have a shortcut for it:

function JQuery(){...} //everything that JQuery does
var $ = JQuery;  //now $() is the shorthand for JQuery()

Again, because it is Javascript, a function can return a value, or another function:

var cheerio = { 
   load: function(start){ 
            return function(end){ return start + " " + end }

var $ = cheerio.load("hello");
$("my friend"); //will return "hello my friend"

In your sample code, $ has been used as a shorthand for ther return value of cheerio.load() function. so, $('#topic_list .topic_title') is equivalent to

cheerio.load(res.text)('#topic_list .topic_title')

meaning that cheerio.load(res.text) is expected to return a function that can later be called. so from the second line of your sample code, $ is nothing but that function. if you had JQuery before that, you can still use JQuery() instead of $().

$element is just a variable name, a visual clue that it is the result of $(element). you could have as easily said var froggy=$(element) but $element is more readable.