Skip to content Skip to sidebar Skip to footer

Typeerror: Cannot Read Property 'foreach' Of Undefined Javascript

Following is the code in which I am getting Cannot read property 'forEach' of undefined. Let me know what I am doing wrong here, though if I do - this is working fine.

Solution 1:

Since there's no semicolon after the function, the snippet gets interpreted as the following:

const print2 = function(x, y) {
  console.log(x*y)
}[1,2,3,4].forEach( x =>print2(x, 20) )

Which means that it's trying to index into the function. Add a semicolon either after the function, or before the array literal:

const print2 = function(x, y) {
  console.log(x*y)
};

[1,2,3,4].forEach( x =>print2(x, 20) )

or

const print2 = function(x, y) {
  console.log(x*y)
}

;[1,2,3,4].forEach( x =>print2(x, 20) )

More about Javascript's automatic semicolon insertion here: What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Solution 2:

You need a semicolon at the end of the variable declaration.

const print2 = function(x, y) {
  console.log(x*y)
};

[1,2,3,4].forEach( x =>print2(x, 20) )

Without the semicolon, it's being treated as

const print2 = function(x, y) {
  console.log(x*y)
}[1,2,3,4].forEach( x =>print2(x, 20) )

[1,2,3,4] is being interpreted as an property accessor, not an array, and the comma operator returns the last value 4. Since the function doesn't have a 4 property, that returns undefined, and then you try to call .forEach() on that.

Solution 3:

You're missing semicolon after FunctionExpression.

const print2 = function(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x =>print2(x, 20) )

change to

const print2 = function(x, y) {
  console.log(x*y)
};

[1,2,3,4].forEach( x =>print2(x, 20) )

and it works.

Solution 4:

I think, rather than [1,2,3,4].forEach( x => print2(x, 20) ), you should use a variable like array.forEach(x => print2(x, 20));

For example code given below:

let array = [1,2,3,4];
const print2 = function(x, y) {
    console.log(x*y);
};

array.forEach( x =>print2(x, 20) );

Solution 5:

For the record. I'll like to add, that I've experienced the same error using that code

var createFiltersList = function() {
        window.filterMenu.forEach(function(text) {     /* <== error here */
            filterList.push({
                text: text,
                expr: text !== ALL ? [DevAV.filterField, "=", text] : null,
                type: DevAV.filterCaption,
                custom: false
            });
        });

        var customItems = JSON.parse(window.localStorage.getItem(storageKey));
        Array.prototype.push.apply(filterList, customItems);
    };

My problem was that I haven't set any value for window.filterMenu so filterMenu was null so forEach is not applicable to null. Once that a set a array of value to filterMenu, the error got away.

Post a Comment for "Typeerror: Cannot Read Property 'foreach' Of Undefined Javascript"