troubleshooting Question

Javascript self invocation and function properties

Avatar of oggiemc
oggiemcFlag for Ireland asked on
7 Comments1 Solution214 ViewsLast Modified:
Hello all,
Im trying to understsnd the attached code..Can someone explain to me whats going on..I understand the syntax of selfinvoking functions and how they are automatically called when defined but i have the following questions regarding this code:

(1) I assume the first function to be called is next() : line 20.
(2) currentIndex = (currentIndex + 1) % foundElements.length;  // What is the meaning of this line? i understand what its doing, but why is it doing it??
(3) Semicolon on line 21 a typo?
(4) Line 23, i assume the search here refers to the outer self invoking function and not the inner search function?
(5) Line 26, same question as (4). How do i access search.results and search.currentIndex from outside the self invoking function??

(6) Line 29, what exactly is being returned?
(7) What is the order of execution in this code? line by line
(8) If i wanted to pass in a value to the function i assume i would do the following modifications:
Line 30 : })(input);
Line 1 : var search = (function (tagName) {

var search = (function () {
    var foundElements = [],
        lastTagName, currentIndex = -1;

    function next() {
        if (foundElements.length === 0) {
            return null;
        currentIndex = (currentIndex + 1) % foundElements.length;
        return foundElements[currentIndex];

    function search(tagName) {
        if (tagName && tagName !== lastTagName) {
            foundElements = documentNode.getElementsByTagName(tagName);
            lastTagName = tagName, currentIndex = -1;
        return next();

    search.results = function () {
        return foundElements.slice();
    search.currentIndex = function () {
        return currentIndex;
    return search;
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 7 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros