Breadth First, in Depth

Here are two different BFS. I used a basic iteration. I didn’t really understand the Java code or explanations on FCC. But I had an idea and wrote my own. Then I googled and found a solution by Lasse Reichstein Nielsen. Then I fixed my own up. Mine is the one using the children approach.

Would it be a good idea to use an Iterable, such as by passing it in?

function breadthFirst(node, callback) {
  let queue = [node];
  for(let i = 0; i < queue.length; i++) {
    let elem = queue[i];
    callback(elem);

    for (let child = elem.firstElementChild; child != null; child = child.nextElementSibling) {
      queue.push(child);
    }
  }
}

let result = "";
breadthFirst(document, el => result += `${el.nodeName} #${el.id||''}, `);

Enqueue children

function breadthFirst2(node, callback) {
  let queue = [node];
  for(let i = 0; i < queue.length; i++) {
    let elem = queue[i];
    callback(elem);
    if(elem.childElementCount > 0) {
      queue = queue.concat(Array.from(elem.children));
    }
  }
}

let result2 = "";
breadthFirst2(document, el => result2 += `${el.nodeName} #${el.id||''}, `);

Compare the results.

document.body.innerHTML = (result.split(",").length) +":<p>"+ result
document.body.innerHTML += (result2.split(",").length) +":<p>"+ result2

Instead of queue = queue.concat(Array.from(elem.children));, queue.push(...elem.children);

Use the most amount of restriction possible.
const queue = [node];