Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while(true) in javascript - how does it work

Tags:

javascript

I've written this code for a Binary Search Tree. For the most part I understand how it works when it comes to inserting nodes. What I don't quite get is the while(true) part.

I'm used to comparing some sort of value when using while loops.

For this code, how does it work?

Is it because I'm setting current and the while loop goes back and checks if that matches the value passed? is that how the while loop works with true?

class Node {
  constructor(val) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

class BinarySearchTree {
  constructor() {
    this.root = null;
  }
}

BinarySearchTree.prototype.insert = function(value) {
  const newNode = new Node(value);

  if (this.root === null) {
    this.root = newNode;
  }

  let current = this.root;

  while(true) {
    if (value === current.val) return;

    if (value < current.val) {
      if (current.left === null) {
        current.left = newNode;
      }

      current = current.left;
    } else {
      if (current.right === null) {
        current.right = newNode;
      }

      current = current.right;
    }
  }
}


let tree = new BinarySearchTree();
tree.insert(10)
tree.insert(5)
tree.insert(13)
tree.insert(11)
tree.insert(2)
tree.insert(16)
tree.insert(7)

console.log(tree);
like image 321
totalnoob Avatar asked Oct 24 '25 03:10

totalnoob


1 Answers

The insert function will iterate, if there are nodes, until it finds a place to put the new node -- either current.right or current.left. After that it will set the current node to either left or right. This means in the next iteration it will check if current.value === value and if true the while(true) infinite loop will be exited which is done by the "return" you could also use "break" instead.

Read this (Does return stop a loop?) to understand how the "return;" works.

Edit: To clear it up, "return" and "break" have different functions but in your case both have the same effect.

like image 120
sascha10000 Avatar answered Oct 26 '25 18:10

sascha10000