TL;DR: A data type tells JavaScript what kind of value something is — text (string), a number, true/false (boolean), nothing (null/undefined), a list (array), or a structured collection (object). Every variable has a type, and mixing them up is one of the most common reasons AI-generated code breaks. The classic example: "2" + 2 gives you "22" instead of 4 because JavaScript treats the "2" as text. Understanding data types means you can spot these bugs before they bite.

Why AI Coders Need This

Every single line of code AI writes involves data types. When Claude builds you a to-do app, the task names are strings. The completion status is a boolean. The list of tasks is an array. Each task with its title, status, and due date is an object. The number of completed tasks is a number.

Here's the problem: JavaScript is loosely typed. That means you can put a number where a string should go, and JavaScript won't stop you — it'll just silently convert one type to the other and keep going. Sometimes the conversion makes sense. Sometimes it produces results that look insane.

According to a 2024 analysis of GitHub issues, type-related bugs account for roughly 15% of all JavaScript errors in production. That number climbs higher in AI-generated code because AI doesn't always track what type a value was three functions ago. It generates code that looks right but mixes types in ways that break at runtime.

You don't need to memorize a type system. You need to recognize the seven types you'll see every day, understand why "2" + 2 doesn't equal 4, and know what to tell your AI when types go wrong. That's what this guide gives you.

The Seven Data Types You'll See Every Day

String — Text

A string is any piece of text. City names, error messages, API keys, URLs, user input — if it's text, it's a string. Strings are always wrapped in quotes.

const userName = "Chuck";
const greeting = 'Welcome back!';
const apiUrl = `https://api.weather.com/v1/${cityName}`;  // template literal

console.log(typeof userName);  // "string"

Notice the three kinds of quotes: double quotes ("..."), single quotes ('...'), and backticks (`...`). The backtick version is called a template literal — it lets you embed variables directly inside the string using ${variableName}. AI uses template literals constantly because they make string building cleaner.

Number — Any Numeric Value

JavaScript uses one type for all numbers — integers, decimals, negatives, zero. There's no separate "integer" or "float" type like some languages have.

const price = 29.99;
const quantity = 3;
const temperature = -5;
const total = price * quantity;  // 89.97

console.log(typeof price);  // "number"

The biggest gotcha with numbers: if a value looks like a number but is wrapped in quotes, it's a string. "29.99" is a string, not a number. This is the root cause of the most common type bug in JavaScript — and we'll get to it in the type coercion section.

Boolean — True or False

A boolean is the simplest type: it's either true or false. No other values. AI uses booleans everywhere for tracking state — is the user logged in? Has the form been submitted? Is the data still loading?

let isLoggedIn = false;
let hasPermission = true;
let isLoading = true;

// Booleans power every if/else decision
if (isLoggedIn) {
  showDashboard();
} else {
  showLoginPage();
}

console.log(typeof isLoggedIn);  // "boolean"

You'll notice a naming pattern: boolean variables almost always start with is, has, can, or should. This convention makes code self-documenting — when you see isLoading, you immediately know it's a true/false value. If your AI names a boolean something vague like status or check, ask it to rename for clarity.

Null — Intentionally Empty

null means "I deliberately set this to nothing." It's a placeholder that says: this variable exists, but it has no value on purpose.

let selectedUser = null;       // no user selected yet
let searchResult = null;       // haven't searched yet
let errorMessage = null;       // no error (yet)

// Later, when the user selects someone:
selectedUser = { name: "Alex", role: "admin" };

console.log(typeof null);  // "object" (yes, this is a famous JavaScript bug)

The typeof null returning "object" is a well-known JavaScript bug from 1995 that was never fixed because too much existing code depends on it. Don't let it confuse you — null is not an object. It means "nothing."

Undefined — Never Assigned

undefined means a variable was created but never given a value. JavaScript assigns it automatically.

let futureValue;
console.log(futureValue);        // undefined
console.log(typeof futureValue); // "undefined"

// Also shows up when accessing properties that don't exist:
const user = { name: "Alex" };
console.log(user.age);           // undefined (no age property)

The practical difference: use null when you want to say "no value." Use undefined to mean "this hasn't been set up yet." In real AI-generated code, you'll see null used as an intentional placeholder far more often than undefined.

Array — An Ordered List

An array is a list of values in a specific order. Think of it as a numbered list — each item has a position (index) starting from 0.

const colors = ["red", "green", "blue"];
const scores = [95, 87, 72, 100];
const mixed = ["hello", 42, true, null];

console.log(colors[0]);       // "red" (first item)
console.log(colors.length);   // 3
console.log(typeof colors);   // "object" (arrays are technically objects)
console.log(Array.isArray(colors));  // true (the real way to check)

Arrays are one of the most common data structures AI generates. Every time your app has a list of anything — users, products, messages, search results — that list is an array. We have a full guide on arrays if you want to go deeper.

Object — A Structured Collection

An object groups related data together using key-value pairs. It's how JavaScript represents anything with multiple properties — a user, a product, a configuration, an API response.

const user = {
  name: "Chuck",
  role: "builder",
  isActive: true,
  projects: 12
};

console.log(user.name);       // "Chuck"
console.log(user["role"]);    // "builder"
console.log(typeof user);     // "object"

Notice how an object can contain different data types — strings, booleans, and numbers all living together under one roof. Objects are everywhere in AI-generated code because API responses almost always come back as objects (or arrays of objects). See our complete guide to objects for more.

Real Scenario: When Data Types Collide

You ask AI to build a shopping cart. It generates code that calculates the total. Everything looks perfect — until a user enters a quantity and the total comes back as "1029.99" instead of 39.98.

Prompt You Might Use

Build a simple shopping cart in JavaScript. The user can enter a
quantity for each item, and the cart should calculate the total price.
Show the total on the page.

AI generates something like this:

// AI-generated shopping cart logic
const price = 29.99;
const quantity = document.getElementById("qty-input").value;
const total = price * quantity;

document.getElementById("total").textContent = "$" + total;

Looks clean. But there's a hidden bug. The .value property of an HTML input always returns a string — even if the user typed a number. So quantity is "2" (string), not 2 (number). Luckily, the * operator forces conversion to a number, so multiplication works here. But if the code used + for addition instead:

const subtotal = quantity + price;
// "2" + 29.99 = "229.99" — string concatenation, not math!

This is where understanding data types saves you. The fix is simple — convert the string to a number explicitly:

const quantity = Number(document.getElementById("qty-input").value);
// Now quantity is 2 (number), and all math works correctly

Type Coercion: Why "2" + 2 = "22"

Type coercion is JavaScript's automatic conversion of one data type to another. It's the single most confusing behavior in the language for new builders, and it causes more silent bugs than almost anything else.

Here's the rule: when you use + and one side is a string, JavaScript converts everything to a string and concatenates (joins) instead of adding:

"2" + 2        // "22"   — string wins, becomes concatenation
"5" + 3        // "53"   — same thing
"Price: " + 10 // "Price: 10" — this is actually useful!
true + 1       // 2      — true becomes 1
false + 1      // 1      — false becomes 0
null + 5       // 5      — null becomes 0
undefined + 5  // NaN    — undefined can't become a number

But other math operators (-, *, /) do the opposite — they convert strings to numbers:

"10" - 3       // 7   — string "10" becomes number 10
"6" * 2        // 12  — works as expected
"8" / 4        // 2   — also works

This inconsistency is why type bugs are so sneaky. Addition with strings concatenates. Subtraction with strings does math. The same value can behave completely differently depending on the operator.

🐛 The Fix When you suspect a value might be a string disguised as a number, explicitly convert it: Number(value), parseInt(value) for whole numbers, or parseFloat(value) for decimals. When debugging, console.log(typeof value) instantly tells you what type you're dealing with.

TypeScript: Why AI Adds Types to Your Code

If you've used Cursor, Claude, or Windsurf, you've probably seen AI generate code that looks like this:

let price: number = 29.99;
let productName: string = "Widget";
let inStock: boolean = true;

function calculateTotal(price: number, quantity: number): number {
  return price * quantity;
}

Those : number, : string, and : boolean labels are TypeScript — a layer on top of JavaScript that catches type errors before your code runs. If you accidentally try to pass a string where a number should go, TypeScript flags it immediately in your editor with a red underline.

AI tools love TypeScript because it prevents exactly the kinds of bugs we've been discussing. Instead of discovering at runtime that "2" + 2 gave you "22", TypeScript would catch the mismatch while you're still writing the code. You don't need to learn TypeScript right now, but knowing why AI adds those type annotations helps you read the code it generates. We cover this in depth in our What Is TypeScript? guide.

What AI Gets Wrong About Data Types

AI coding tools are remarkably good at generating working code — until types get involved. Here are the three most common type-related mistakes you'll encounter:

1. Implicit Coercion in Comparisons

AI sometimes uses == (loose equality) instead of === (strict equality). The double-equals version does type coercion before comparing, which leads to bizarre results:

// With == (loose — coerces types)
0 == ""       // true  (both coerce to 0)
0 == false    // true  (both coerce to 0)
"" == false   // true  (both coerce to 0)
null == undefined  // true  (special case)

// With === (strict — no coercion)
0 === ""      // false (number vs string)
0 === false   // false (number vs boolean)
"" === false  // false (string vs boolean)
null === undefined  // false (different types)

The fix: Always use ===. If your AI generates ==, ask it to switch to strict equality. This one change prevents an entire class of bugs.

2. Null vs. Undefined Confusion

AI sometimes initializes variables with undefined when it should use null, or doesn't handle both cases when checking for empty values:

// AI might generate:
let user = undefined;  // ❌ Should be null (intentional "no value")

// And then check only one:
if (user === null) {
  // This won't catch undefined!
}

// Better pattern:
let user = null;       // ✅ Intentionally empty
if (user == null) {    // This is the ONE good use of == 
  // Catches both null AND undefined
}

The fix: Initialize empty values with null. When checking for "no value," use == null (the one case where loose equality is actually helpful) or check both explicitly: if (user === null || user === undefined).

3. Mutating Objects and Arrays Declared with const

AI declares objects and arrays with const, which prevents reassignment — but it doesn't prevent changing the contents. This confuses new builders who think const means "can't change":

const user = { name: "Alex", role: "viewer" };
user.role = "admin";  // ✅ This works! const doesn't freeze the object.

const items = [1, 2, 3];
items.push(4);        // ✅ This also works!

// What const actually prevents:
user = { name: "New" };  // ❌ TypeError: can't reassign const
items = [5, 6, 7];       // ❌ TypeError: can't reassign const

Why it matters: If AI passes an object to a function and that function modifies properties, the original object changes too — even though it was declared with const. This is called mutation, and it's a common source of bugs where data changes unexpectedly. When you see mysterious state changes, check if a function is modifying an object that was passed to it.

What to Learn Next

Now that you understand data types, you have the vocabulary to go deeper into the structures AI uses most:

Frequently Asked Questions

What are the main data types in JavaScript?

JavaScript has seven core data types you'll encounter in AI-generated code: string (text like "hello"), number (any numeric value like 42 or 3.14), boolean (true or false), null (intentionally empty), undefined (declared but not assigned), object (a collection of key-value pairs), and array (an ordered list). Technically arrays are a special type of object, but they behave differently enough that developers treat them as their own category.

Why does "2" + 2 equal "22" in JavaScript?

This happens because of type coercion. When JavaScript sees the + operator with a string on one side, it converts everything to a string and concatenates (joins) them. So "2" + 2 becomes "2" + "2" which equals "22" — a string, not the number 4. To get the number 4, convert the string first: Number("2") + 2 or parseInt("2") + 2.

What is the difference between null and undefined?

Both mean "no value," but they mean it differently. undefined means a variable was declared but never given a value — JavaScript assigned it automatically. null means someone intentionally set the value to "nothing" as a placeholder. Think of undefined as an empty shipping label (nobody wrote an address yet) and null as a label that says "no address on file" (deliberately marked empty). In practice, use null when you want to say "no value yet" on purpose.

How do I check what data type a variable is?

Use the typeof operator: typeof "hello" returns "string", typeof 42 returns "number", typeof true returns "boolean". There are two gotchas: typeof null returns "object" (a famous bug), and typeof [1,2,3] also returns "object". To check for arrays specifically, use Array.isArray([1,2,3]) which returns true.

Why does AI-generated code sometimes add TypeScript types?

TypeScript adds explicit type labels (like : number or : string) so bugs get caught before your code runs. Instead of discovering at runtime that "2" + 2 gave you "22", TypeScript flags the mismatch while you're still writing. AI tools add TypeScript types because they prevent exactly the category of bugs that type coercion causes — catching mismatched types at write-time instead of when your app crashes in front of a user.