Loops in NodeJS

Can someone help me with loops in NodeJS :point_right::point_left:

2 Likes
For loops

For in:

for (index in array) {
    console.log(array[index])
}

For of:

for (item of array) {
    console.log(item)
}

For index (@SharkCoding):

for (let i = 0; i < array.length; i++) {
    console.log(array[i]);
}

ForEach (@9pfs reminded me these exist):

array.forEach(function(value, index, arr) {
    console.log(`${index} is ${value} (${arr})`)
});
While loops

While condition:

while (condition) {
    console.log("Looping!")
}

While true:

while (true) {
    console.log("Infinite loop")
}
// Or
while (!![]) {
    console.log("Also infinite")
}

While something is not empty, null, or undefined:

while (!!something) {
    console.log("Not empty!")
}
Do While

Similar format to normal while:

do {
   console.log("Condition is false, but I'm called once!")
} while (false)
2 Likes

what kind of loop? async using setInterval, for loops or while loops?

2 Likes

also those for loops don’t work. You can only use that notation to loop through each key of an object. to loop through each item of an array you have to do this:

You can also do it like this, it offers more control over the loop.

let arr = [2,3,4,3,6];

for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

and to loop through each key of an object

let obj = {
    a: 4,
    b: 6,
    c: 2
};

for (key in obj) {
    console.log(key);
}
2 Likes

I know the index one I provided does work, I do that a lot actually.

2 Likes

Thanks

I s-uck at node xD

bro im not allowed to say s-uck

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

I could help?

3 Likes

yeah if u want
i know js pretty well now tho