2

Is it possible to use const with while loop in JS. I wonder if we can do something like this without using recursive function:

const node = current;
while (!found(node)) {
    node = node.previous
}

How do they do it in functional programming style?

Clite Tailor
  • 438
  • 5
  • 14

2 Answers2

2

No. const means constant.
The value of a const can never, ever, ever change, for the lifespan of that invocation.

let cur;
while (!found(cur)) {
  node = node.previous;
  // do stuff
  cur = // ...
}

That will work just fine.

Likewise

for (let i = 0; i < stuff.length; i += 1) {
  const thing = stuff[i];
  // do stuff with a thing
}

Here the const lives as long as one single iteration through the loop.
Outside of the loop, it would live through every iteration, which means that it won't be recreated, which means it can't be reassigned through that whole loop (or through any other part of the function), because it's a constant.

Neither of these is particularly functional, however.

It is very possible to do FP without recursion, but neither of these setups is a way of accomplishing such. I'd recommend learning about map/filter/reduce and thought patterns for structuring collections to support those techniques, if you're looking to avoid mutating state inside of code that you maintain. Because loops with consts (which throw on reassignment) isn't going to do it.

Norguard
  • 26,167
  • 5
  • 41
  • 49
2

Functional style does not use while loops, so the only way to do this would be using recursion. If your node is an object which has current and previous fields, a more "functional" way would be to do:

function find(startNode) {
    if (!found(startNode)) {
      if (startNode.previous) {
        return find(startNode.previous)
      } else { 
        return null
      }
    } else {
      return startNode
    }
}

And then call find on the initial node.

Pedro Castilho
  • 10,174
  • 2
  • 28
  • 39