Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  182] [ 3]  / answers: 1 / hits: 13237  / 4 Years ago, tue, april 7, 2020, 12:00:00

It's known that in general, JavaScript allows an inline for loop in the format:



someArray.forEach(x => x.doSomething());


However, when one wants to use a regular for-loop inline, as one statement, an error is occured. For example:



void(for(var i = 0; i < 0; i++) console.log(i));


Even though this is technically one line, but since it's used in a format of literally being inline, and being considered one statement, it gives the error:




Uncaught SyntaxError: Unexpected token 'for'




Why might one want to do this? Simple: in order to generate an array, or string, in one line, for example:



var newString = (let k = , for(let i = 0; i < 1000; i++) k+= i, k);


But this gives an obvious




Uncaught SyntaxError: Unexpected identifier




error, because of the let keyword, but that's a different question.



Mainly, is it possible to make a regular for-loop inline in JavaScript?


More From » arrays

 Answers
7

Here is a single line IIFE (Immediately Invoked Function Expression):





let newString = (() => {let concatenatedString = ''; for (let i = 0; i < 1000; i++) {concatenatedString+= i;} return concatenatedString;})();

console.log(newString);








Further Reading on IIFEs:




[#4241] Saturday, April 4, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blaisep

Total Points: 748
Total Questions: 95
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
blaisep questions
Wed, Dec 16, 20, 00:00, 4 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
Tue, Nov 12, 19, 00:00, 5 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
Tue, Oct 15, 19, 00:00, 5 Years ago
;