Javascript: Invalid Destructuring Target

Javascript: Invalid Destructuring Target

Here is the code:

 function BinarySearchNode(key) {
     let node = {};
     node.key = key;
     node.lft = null;
     node.rgt = null;

     node.log = () => {
         console.log(node.key);
     }

     node.get_node_with_parent = (key) => {
         let parent = null;

         while (this) {
             if (key == this.key) {
                 return [this, parent];
             }

             if (key < this.key) {
                 [this, parent] = [this.lft, this];
             } else {
                 [this, parent] = [this.rgt, this];
             }
         }

         return [null, parent];
     }

     return node;
 }

My Firefox is 44.0 and it throws a SyntaxError for these lines:

if (key < this.key) {
    [this, parent] = [this.lft, this];
} else {

I tried to understand what exactly is wrong here by reading this blogpost and the MDN. Unfortuntely, I am still missing it :(

3

1 Answer

this is not a variable, but a keyword and cannot be assigned to. Use a variable instead:

node.get_node_with_parent = function(key) {
    let parent = null;
    let cur = this; // if you use an arrow function, you'll need `node` instead of `this`
    while (cur) {
        if (key == cur.key) {
            return [cur, parent];
        }
        if (key < cur.key) {
            [cur, parent] = [cur.lft, cur];
        } else {
            [cur, parent] = [cur.rgt, cur];
        }
    }
    return [null, parent];
}
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.