How to do an inline for loop in JavaScript, that's not connected to a variable
Asked Answered
M

3

8

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?

Macaque answered 7/4, 2020 at 10:58 Comment(2)
You can always use an IIFE.Gytle
@Gytle whats thatHessler
E
8

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:

Escaut answered 7/4, 2020 at 11:10 Comment(0)
W
1

for is a statement not a expression you can't use it at right hand side of variable assignment. You also don't have to use void. Just simply use the loop

for(var i = 0; i < 4; i++) console.log(i)
Woodworm answered 7/4, 2020 at 11:1 Comment(3)
true, although the void was just an example to be able to use it with the comma operator, for example (for(var i = 0; i < 4; i++) console.log(i), someOtherThingWith(i))Hessler
@bluejayke You can't use comma operator between statements. Because statements doesn't return anything. And for is a statement.Woodworm
but that's the problem, is there some kind of for loop that would return a value, yet work the same way, or is there a way to use a statement as an expression?Hessler
D
0

Why would you specifically need a for loop in one line? It looks less readable. Why not just warp your for loop in a function?

function functionName(number) {
    let temp = 0;
    let i = 0;

    for (i; i < number; i++) {
        temp += i;
    }

    return temp;
}

const value = functionName(5);

console.log(value);
Dixiedixieland answered 7/4, 2020 at 12:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.