Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't 'return' stop the function completely inside an 'if' statement?

Tags:

javascript

dom

I'm currently doing this small tutorial on accessing the DOM. Right at the bottom of the page, there's a small excersise on creating a function to go through all the nodes in the DOM and get the next node. I've got the code working, but I'm not sure exactly HOW it's working. This is less to do with the DOM and more to do with if/while loops.

This is the code:

nextNode = function(node) {
    if (node.firstChild) {
        return node.firstChild;
    }

    while (node) {
        if (node.nextSibling) {
            return node.nextSibling;
        }
        node=node.parentNode;
    };
    return node;
};

My questions are:

  1. What is the first step that this function will take? For instance, it first checks if there's a child node for the selected node. If there is, it'll 'return' it. Shouldn't this end the function? I thought returning was a way to break out of a function? Why does it continue?

  2. When it continues on to the while loop, it checks if there's a next sibling. It 'returns' this too. What is it returning it to? It then jumps to the parent node, and then checks again.

I hope my question makes sense. I'm just trying to understand the steps that are being taken during the execution of this function.


1 Answers

The return works as you suppose it does - it terminates the function call completely. What your function does is basically a single step in deep DOM tree walkthrough:

  1. checks whether the node has a child and returns it if it does. If it doesn't,
  2. checks whether the node has a following sibling and returns it if it does. If it doesn't,
  3. checks whether the node's parent has a following sibling and returns it if it does (loops recursively). If there is really no following node,
  4. returns null, (because it exits the while loop only when node isn't defined).
like image 69
hon2a Avatar answered Mar 21 '26 21:03

hon2a



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!