Brainlag
  1. Library
  2. Debugging
  3. Web

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.

Web5 min

What JavaScript is telling you

Output
TypeError: tags.forEach is not a function

The 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, map and push belong to arrays. If tags is actually a string or an object, they are not there.
  • A misspelt method. toUppercase() instead of toUpperCase(), or lenght().
  • A name reused. let total = 0; then later total(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.

main.js to run
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:

Output
#lofi
#study
#beats

It crashes instead. Fix it without typing the tags out by hand.

exercise_1.js to run
const tagsFromForm = "lofi,study,beats";
tagsFromForm.forEach((tag) => {
  console.log("#" + tag);
});

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.