Pida's avatar
Level 7

JavaScript for ... of breaks when using Mix

I just moved some JavaScript code from a Blade file to a separate JavaScript file in the assets/js directory. I use Laravel Mix without any modifications (my devDependencies contain "laravel-mix": "^2.0", and I run npm run dev to compile my assets).

Something in this process is breaking my code, more precisely this for ... of loop inside a Vue method:

for (date of dates) { // date is undefined in this line already)
    console.log(date);
}

This variation using forEach is working:

dates.forEach(function(date) {
    console.log(date);
});

What is happening here?

0 likes
4 replies
D9705996's avatar
D9705996
Best Answer
Level 51

Have you tried using let to set the scope of date? e.g.

for (let date of dates) {
  console.log(date);
}

This blog might help. Personally I would stick with the forEach implementation as I find it more readable.

Pida's avatar
Level 7

I can't believe I simply forgot to use let, I usually do so and I didn't even know it's possible to do a for ... of loop without let or var - though apparently it breaks when babelizing. Thank you!

I prefer for .. of at least in this case for reasons that aren't apparent in my simplified code sample: I need to access this (which is not accessible to forEach unless used as a second argument) and I also need to short circuit the loop under certain conditions (break doesn't work in forEach).

D9705996's avatar

@PIDA - For reference you could use an arrow function with forEach as it won't bind this

dates.forEach((date) => {
    console.log(this);  //outputs this from outside the for each.
});

You could combine arrow functions with some instead of forEach to short circuit the loop.

1 like
Pida's avatar
Level 7

Thanks, that's an interesting approach. I wouldn't use it in this case because to me, this

for (let date of dates) {
    doSomething();

    if (someCondition) {
        break;
    }
}

is more readable/maintainable than this

dates.some((date) => {
    doSomething();
    
    return (someCondition);
});

Please or to participate in this conversation.