dezman
dezman

Reputation: 19368

Why can't I assign for loop to a variable?

So I am just wondering why the following code dosen't work. I am looking for a similar strategy to put the for loop in a variable.

var whatever = for (i=1;i<6;i++) {
console.log(i)
};

Thanks!

Upvotes: 0

Views: 215

Answers (4)

Travis J
Travis J

Reputation: 82297

You can do this, but it seems that you might want to check out anonymous functions. With an anonymous function you could do this:

var whatever = function(){
 for (var i=1;i<6;i++) {
  console.log(i);
 }
};

and then

whatever(); //runs console.log(i) i times.

Upvotes: 0

raina77ow
raina77ow

Reputation: 106443

I suppose what you look for is function:

var whatever = function(min, max) {
  for (var i = min; i < max;  ++i) {
    console.log(i);
  }
}

... and later ...

whatever(1, 6);

This approach allows you to encapsulate the loop (or any other code, even declaring another functions) within a variable.

Upvotes: 2

blearn
blearn

Reputation: 1208

Your issue is that for loops do not return values. You could construct an array with enough elements to hold all the iterations of your loop, then assign to it within the loop:

arry[j++] = i;

Upvotes: 0

Pointy
Pointy

Reputation: 413846

Because a for loop is a statement and in JavaScript statements don't have values. It's simply not something provided for in the syntax and semantics of the language.

In some languages, every statement is treated as an expression (Erlang for example). In others, that's not the case. JavaScript is in the latter category.

It's kind-of like asking why horses have long stringy tails and no wings.

edit — look into things like the Underscore library or the "modern" add-ons to the Array prototype for "map" and "reduce" and "forEach" functionality. Those allow iterative operations in an expression evaluation context (at a cost, of course).

Upvotes: 5

Related Questions