0

Wondering if there is by any chance to programmatically setting third statement of forloop

var conditionProgrammatically = 'i++';//or 'x--'

for (var i = 0; i < 10; conditionProgrammatically) {
  console.log(i)
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Isaac
  • 12,042
  • 16
  • 52
  • 116

3 Answers3

4

You can use any expression you want there including calling a function. You just need to be careful of scope. So, for example, this works:

var conditionProgramatically = () => i++ ;

for (var i = 0; i < 10; conditionProgramatically()) {
  console.log(i)
}

But it depends on the fact that var i is in a scope shared by the function. This, however, doesn't work:

var conditionProgramatically = () => i++ ;

for (let i = 0; i < 10; conditionProgramatically()) {
  console.log(i)
}

Because let is scoped to the block and not available.

Of course you can share an object which is mutable by passing it as an argument like:

fn = (o) => o.i += 1
for (let o = {i:0}; o.i < 10; fn(o)) {
    console.log(o.i)
  }
  

This allows you to use let, but is a little hard on the eyes.

All said, it's probably going to be easier to make your logic fit in a simple expression rather than calling a function. You can still perform some logic, though:

for (let i = 0; Math.abs(i) < 10; i = Math.random() > .65  ? i -1: i + 1) {
  console.log(i)
}
Mark
  • 90,562
  • 7
  • 108
  • 148
1

You can set a variable and then operate with this variable according to your needs. (remember that i-- is equivalent to i -= 1). BTW, be careful because you would also have to change the condition, if not you will end up in an infinite loop. In your case, I would use abs()

var step = 1; // or var step = -1;
for (var i = 0; abs(i) < 10; i += step) {
  console.log(i)
}
  • How is this different to the example in the question? – coagmano Jun 29 '18 at 04:26
  • `conditionProgramatically` holds a string value on the question. :) – Eddie Jun 29 '18 at 04:28
  • 1
    The difference is that you are not using text (that would have to be analyzed with eval or other unsafe method) but a (much easier to handle) variable. –  Jun 29 '18 at 04:29
  • If you think this is the same code as in the question, perhaps you need a refresher course in javascript – Jaromanda X Jun 29 '18 at 04:40
1

Usually, in functional programmings (like python and javascript), we can use dictionary (or objects) to store functions.

var myFunctions = {
  "a": function (i) { return i + 1 },
  "b": function (i) { return i - 3 }
};

Then, we can set the condition as the key to the dictionary:

myCondition = "a"; // this will set condition to increment by 1

Here is your for loop:

for (i = 0; i < n; i = myFunctions[myCondition](i)) {
  // whatever
}
Edward Aung
  • 3,014
  • 1
  • 12
  • 15