-1

I have heard that the for(){...} loop in JavaScript is passé and should not be used in favor of other, clearer alternatives. JSLint goes so far as to throw an error when it encounters one (unless you override it, of course). I understand using Array.prototype.forEach() when the situation allows, but in this instance what alternative could I use that would be "clearer"?

var number = 5;
for (var i=0; i <= number; i++){ 
    log("somestring" + i);
}

In C# I would use a foreach(){...} over Enumerable.Range(0, 5) - but I know of no such alternative in JavaScript. I could create an array of digits 0...5 but that seems like going the long way for no gain.

Edit 1

I am not looking for an alternative plugin to implement this like lodash or jQuery, and my question really isn't about "why does JSLint...". What native JavaScript alternative would I use?

Scott Baker
  • 10,013
  • 17
  • 56
  • 102

2 Answers2

1

return is not a good idea in between a loop in javascript.this overridden due to the same you can use break or continue instead to break the execution in between. There also to get the data as foreach jquery also allowed object map to the same as follows. and get the value for each as a dynamic string you can work as per the function is given below.

var number = 5;
var toReturn = function(){
var ar_data = []; 
for (var i=0; i <= number; i++){ 
    ar_data[i] = "somestring" + i;  // Store your dynamic string into a variable
}
return ar_data; // return array 
}
var data = toReturn(number);

for(dt in data) // foreach type object mapping and tracing 
{
console.log(data[dt]); //print the individual item in array.
}
A.D.
  • 2,352
  • 2
  • 15
  • 25
0

If you're using an array to store your numbers, use .reduce():

const num = [1, 2, 3, 4, 5]
const val = num.reduce((acc, curr) => `${acc}${curr}`, 'somestring')
console.log(val)

Edit: The thing is, if you don't want to use an array then the for loop would be the most readable. My advice is to just ignore what JSLint says.

I'll just post another suggestion. It uses the array indexes to generate an array:

[...Array(5).keys()].reduce((acc, curr) => `${acc}${curr + 1}`, 'somestring')
Jaye Renzo Montejo
  • 1,812
  • 2
  • 12
  • 25