Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: why .forEach doesn't work?

Here is a little piece of code:

window.addEventListener('load', function() {
    ['echo'].forEach(function(entity) {
        console.log('loaded entity=' + entity)
    })
})

console.log(['echo'])
console.log(['echo'].forEach)
['echo'].forEach(function(entity) {
    console.log('entity=' + entity)
})

Output looks like this:

["echo"]
function forEach() { [native code] }
Uncaught TypeError: Cannot read property 'echo' of undefined
loaded entity=echo

Why does this error occur? I assume that undefined is this inside .forEach. Why doesn't it get passed when calling .forEach?

like image 719
Pijusn Avatar asked Jan 29 '26 01:01

Pijusn


1 Answers

SEMICOLONS!

window.addEventListener('load', function() {
    ['echo'].forEach(function(entity) {
        console.log('loaded entity=' + entity);
    })
});

console.log(['echo']);
console.log(['echo'].forEach);
['echo'].forEach(function(entity) {
    console.log('entity=' + entity);
});

The problem is here:

console.log(['echo'].forEach)
['echo'].forEach(function(entity) {

The line break is ignored, at it gets parsed as this:

console.log(['echo'].forEach)['echo'].forEach(function(entity) {

console.log() returns undefined, and undefined['echo'] raises an exception.

So use semicolons and be happy. Or don't and suffer.

like image 197
Alex Wayne Avatar answered Jan 30 '26 15:01

Alex Wayne