Esa Mäkinen
Esa Mäkinen

Reputation: 160

Cheerio each loop does not break out early

In the Cheerio/Jquery documentation it is stated, that return false should break each loop early.

I have the following code:

"use strict";
let cheerio = require('cheerio');
let $ = cheerio.load('<a href="www.test.com"></a><a href="www.test.com"></a>');

$('a').each(function(index,value){
  console.log(index);
  return false;
});

It should, in my head, print 0 to console, but it prints 0 and 1. What am I missing?

Upvotes: 1

Views: 2340

Answers (1)

Asish Bhattarai
Asish Bhattarai

Reputation: 502

The code is fine. If you look at cheerio's source code, you can see that there is no way the loop continues if you return false.

https://github.com/cheeriojs/cheerio/blob/master/lib/api/traversing.js#L298

exports.each = function(fn) {
  var i = 0, len = this.length;
  while (i < len && fn.call(this[i], i, this[i]) !== false) ++i;
  return this;
};

Upvotes: 2

Related Questions