BugHunt

TypeError: data.map is not a function

The value exists, but it is not an array. Usually an object wrapping the array, a JSON string you have not parsed, or a NodeList.

JavaScriptType errors

What it means

map lives on Array.prototype only. The value is defined — otherwise the error would be "Cannot read properties of undefined" — but it is some other type. console.log(typeof data, Array.isArray(data)) answers it in one line.

Common causes

1. The API returned an object, not an array

Most APIs send { data: [...] } or { items: [...], total: 50 }.

Breaks

const res = await fetch("/api/users");
const users = await res.json();
users.map(u => u.name);

Works

const { items } = await res.json();
items.map(u => u.name);

2. An object you meant to iterate

Plain objects have no map. Object.values, keys or entries give you an array.

Breaks

const scores = { ada: 3, bo: 5 };
scores.map(s => s * 2);

Works

Object.entries(scores).map(([name, s]) => [name, s * 2]);

3. A JSON string that was never parsed

localStorage and some fetch wrappers hand back strings. Strings have no map.

Breaks

const todos = localStorage.getItem("todos");
todos.map(t => t.title);

Works

const todos = JSON.parse(localStorage.getItem("todos") ?? "[]");
todos.map(t => t.title);

4. A NodeList or Set

querySelectorAll returns a NodeList, which has forEach but not map. Sets have neither.

Breaks

document.querySelectorAll("li").map(li => li.textContent);

Works

Array.from(document.querySelectorAll("li"), li => li.textContent);

How to find it in your own code

Log Array.isArray(value) and the value itself. Then either reach into it for the actual array, convert it (Array.from, Object.values, JSON.parse), or fix the producer so it always returns an array.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Other common errors