bobNelson
bobNelson

Reputation: 38

why does this javascript add () function for a linked list return node?

I'm working through understanding how this singly linked list implementation works in JavaScript. Specifically, the return statements on lines 23 and 35 in the add() method.

-- On line 23, why would we return node, instead of using 'return'; instead? -- On line 35, why would we return node when it doesn't seem to affect the functionality of the code either way?

Thanks!

    // Constructors (Node and SinglyList)
    function Node(data) {
        this.data = data;
        this.next = null;
    }

    function SinglyList() {
        this._length = 0;
        this.head = null;
    }

    //Add Method

    SinglyList.prototype.add = function(value) {
        var node = new Node(value),
            currentNode = this.head;

        if(!currentNode) {
            this.head = node;
            this._length++;

            // return the new Node object. (why can't we just use return; here?)
            return node;
        }

        //USE CASE 2: NON-EMPTY LIST
        while (currentNode.next) {
            currentNode = currentNode.next; 
        }
        currentNode.next = node;

        this._length++;

        // return statement doesn't seem to do anything here.
        return node;
    };

    var list = new SinglyList();
    list.add(1);
    list.add(2);
    list.add('foo');
    console.log(list.head);

Upvotes: 0

Views: 206

Answers (1)

David Li
David Li

Reputation: 1290

The author of this SinglyList simply wanted to implement it that way.

In the use case that the user wants a reference to the new node that was created in the list, they could save that rather than finding that node again after the add. There is no single correct way to implement a LinkedList, and a lot is left up to interpretation.

In the event that you don't want the reference after adding the node, you can just choose to ignore the returned element.

Upvotes: 1

Related Questions