is not a functionWhat is "is not a function"?
This TypeError means you put brackets after something that is not a function. Usually a method on the wrong type, like forEach on a string, or a misspelt method name.
What JavaScript is telling you
TypeError: tags.forEach is not a functionThe brackets in tags.forEach(...) mean "call this". JavaScript looked up tags.forEach, found something that is not a function (usually undefined), and could not call it.
The usual reasons:
- The wrong type.
forEach,mapandpushbelong to arrays. Iftagsis actually a string or an object, they are not there. - A misspelt method.
toUppercase()instead oftoUpperCase(), orlenght(). - A name reused.
let total = 0;then latertotal(cart): the name now holds a number, not your function.
How to find it
The message names the exact expression it tried to call. Log the part before the dot and its type: console.log(typeof tags, tags). If it says string when you expected an array, find where that value came from. If the type is right, check the method name letter by letter against the docs.
Run it: a string pretending to be a list
Press Run and read the error from the bottom up.
const post = {
author: "kofi99",
tags: "gaming, speedrun, minecraft",
};
post.tags.forEach((tag) => {
console.log("#" + tag);
});
Hashtags that will not print
The tags come in as one line of text from a form. This should print each one as a hashtag:
#lofi
#study
#beatsIt crashes instead. Fix it without typing the tags out by hand.
const tagsFromForm = "lofi,study,beats";
tagsFromForm.forEach((tag) => {
console.log("#" + tag);
});