JavaScript Values and Types: Number, String, Boolean, null, undefined

JavaScript code works with values, and every value has a type. Understanding the basic types, such as Number, String, Boolean, null, and undefined, is one of the fastest ways to write code that behaves predictably.

Quick answer: JavaScript values are the pieces of data your code stores and uses. The most common basic types are number, string, boolean, null, and undefined; each one represents a different kind of value and is used differently.

Difficulty: Beginner

You'll understand this better if you know: basic variables, simple expressions, and how to read a line of JavaScript code.

1. What Is JavaScript Values and Types: Number, String, Boolean, null, undefined?

In JavaScript, a value is any piece of data your program can store, pass around, compare, or display. A type describes what kind of value it is and what you can do with it.

  • Number represents numeric values such as 42 or 3.14.
  • String represents text such as "hello".
  • Boolean represents logical values: true or false.
  • null represents an intentional absence of a value.
  • undefined represents a value that has not been assigned yet.

These are the core building blocks behind variables, conditions, comparisons, and many common bugs. If you understand them well, reading JavaScript becomes much easier.

2. Why JavaScript Values and Types Matter

Types matter because JavaScript changes its behavior depending on the kind of value you give it. The same operator can produce very different results with numbers and strings, and missing values can create logic bugs if you do not handle them carefully.

For example, adding numbers gives arithmetic, but adding strings joins text. A variable with undefined is often a sign that something was not initialized, while null often means you intentionally cleared or reset a value.

Knowing the difference helps you:

  • avoid unexpected type coercion
  • write safer condition checks
  • debug form values, API responses, and optional data
  • understand error messages that mention types

3. Basic Syntax

JavaScript does not require you to declare the type of a variable up front. The type comes from the value you assign.

Declaring values

The following example shows one variable for each basic type:

JavaScript
const age = 28;// number
const name = "Mina";// string
const isLoggedIn = true;// boolean
const middleName = null;// intentional empty value
let pendingResult;// undefined

Here, age, name, and isLoggedIn each hold a different type of value. middleName is set to null, and pendingResult is undefined because no value has been assigned yet.

Checking a type

You can inspect many values with the typeof operator:

JavaScript
typeof 42;// "number"
typeof "hello";// "string"
typeof true;// "boolean"
typeof undefined;// "undefined"

One special case is that typeof null returns "object", which is a long-standing JavaScript quirk. That is one reason many developers check null directly instead of relying on typeof.

4. Step-by-Step Examples

Example 1: Numbers for counting and math

Use Number values when you need arithmetic, counters, measurements, or indexes.

JavaScript
const price = 19.99;
const quantity = 3;
const total = price * quantity;

console.log(total); // 59.97
Output✓ Tested · Node 24
59.97

This shows numeric multiplication. JavaScript supports integers and decimals in the same Number type.

Example 2: Strings for text

Use String values for names, labels, messages, and user input.

JavaScript
const firstName = "Ada";
const lastName = "Lovelace";
const fullName = firstName + " " + lastName;

console.log(fullName); // "Ada Lovelace"
Output✓ Tested · Node 24
Ada Lovelace

String addition with + joins text together. This is different from adding numbers.

Example 3: Booleans for decisions

A Boolean value is usually the result of a comparison or a condition check.

JavaScript
const temperature = 22;
const isWarm = temperature > 18;

if (isWarm) {
  console.log("It feels warm enough.");
}
Output✓ Tested · Node 24
It feels warm enough.

Here, the comparison creates a true or false value, which then controls the if statement.

Example 4: null for intentional emptiness

Use null when a value is deliberately empty or not yet available, but you want that emptiness to be explicit.

JavaScript
const selectedUser = null;

if (selectedUser === null) {
  console.log("No user selected yet.");
}
Output✓ Tested · Node 24
No user selected yet.

This pattern is common when a value will be filled in later, such as after a user clicks a button or loads data.

Example 5: undefined from missing assignment

When a variable is declared but not assigned, its value is undefined.

JavaScript
let score;

console.log(score); // undefined

score = 10;
console.log(score); // 10
Output✓ Tested · Node 24
undefined
10

This is one of the clearest examples of how JavaScript represents a value that exists in name but not yet in content.

5. Practical Use Cases

  • Number: prices, ages, scores, timestamps, and loop counters.
  • String: user names, email addresses, labels, JSON text, and error messages.
  • Boolean: feature flags, login state, validation results, and visibility toggles.
  • null: cleared form fields, missing database relationships, and intentionally empty selections.
  • undefined: uninitialized variables, missing function arguments, and absent object properties.

These values appear constantly in browser apps, Node.js programs, and API-driven code. Even a small bug in one of these types can affect calculations, rendering, or conditional logic.

6. Common Mistakes

Mistake 1: Confusing number values with numeric strings

Values from forms, query strings, and text files often look like numbers but are actually strings. That difference matters because string concatenation is not the same as numeric addition.

Problem: This code adds two strings, so the result is text instead of a true numeric sum.

JavaScript
const a = "5";
const b = "10";

const result = a + b;
console.log(result); // "510"
Output✓ Tested · Node 24
510

Fix: Convert the values to numbers before doing math.

JavaScript
const a = "5";
const b = "10";

const result = Number(a) + Number(b);
console.log(result); // 15
Output✓ Tested · Node 24
15

The corrected version works because both operands are actual numbers before the addition happens.

Mistake 2: Treating null and undefined as the same thing

They are related, but they mean different things. null usually means intentional emptiness, while undefined usually means no value has been assigned or supplied.

Problem: This code assumes every missing value should be handled the same way, which can hide a real bug in your data flow.

JavaScript
function showProfile(user) {
  if (user == null) {
    console.log("No user available.");
  }
}

Fix: Decide whether you want to check for only null, only undefined, or both.

JavaScript
function showProfile(user) {
  if (user === null) {
    console.log("User was intentionally cleared.");
  } else if (user === undefined) {
    console.log("User was never assigned.");
  }
}

The corrected version keeps the meanings separate, which makes bugs easier to find.

Mistake 3: Relying on truthiness when you need an exact type check

JavaScript treats some values as falsy, including 0, "", null, undefined, and false. That can be useful, but it can also hide valid values like 0.

Problem: This code treats 0 the same as an empty or missing value, so a real score of zero is ignored.

JavaScript
const score = 0;

if (score) {
  console.log("Score is available.");
} else {
  console.log("No score yet.");
}
Output✓ Tested · Node 24
No score yet.

Fix: Check for null or undefined directly when zero is a valid value.

JavaScript
const score = 0;

if (score !== undefined && score !== null) {
  console.log("Score is available.");
} else {
  console.log("No score yet.");
}
Output✓ Tested · Node 24
Score is available.

The corrected version works because it checks for missing values without rejecting 0.

7. Best Practices

Practice 1: Use strict equality for exact comparisons

When you want to compare values without type conversion, use === instead of loose equality. This avoids surprises caused by automatic coercion.

JavaScript
const age = "18";

if (age === 18) {
  console.log("Adult");
}

This comparison is false because the types differ. If you want a real numeric comparison, convert first.

Practice 2: Be explicit when converting values

Instead of depending on automatic conversion, convert strings to numbers or numbers to strings at the boundary where the change is needed.

JavaScript
const input = "42";
const count = Number(input);

console.log(count + 8); // 50
Output✓ Tested · Node 24
50

Clear conversion makes the code easier to read and debug than letting JavaScript decide for you.

Practice 3: Use null for intentional empty state

If a variable starts empty by design, null often communicates your intent better than leaving it undefined.

JavaScript
let selectedItem = null;

function chooseItem(item) {
  selectedItem = item;
}

This makes the initial state clear: nothing is selected yet, but that emptiness is intentional.

8. Limitations and Edge Cases

  • typeof null returns "object", so it is not a reliable way to detect null.
  • NaN is a special Number value that means “not a number,” but its type is still number.
  • Infinity and -Infinity are valid numeric values in JavaScript.
  • Empty strings, 0, and false are falsy, which can break simple condition checks.
  • Missing object properties usually evaluate to undefined, not null.
  • Different APIs and libraries may use null or undefined differently, so you should read the contract carefully.

One especially common search problem is “why is my value undefined?” In many cases, the value was never assigned, a property name is misspelled, or the data has not loaded yet.

9. Practical Mini Project

Let us build a tiny profile summary that shows how these values work together. The example stores a user name, an age, a premium status, and an optional nickname.

JavaScript
const profile = {
  name: "Jordan",
  age: 31,
  isPremium: true,
  nickname: null
};

const nicknameText = profile.nickname === null
  ? "No nickname set"
  : profile.nickname;

const summary =
  profile.name + " is " + profile.age + " years old. Premium: " + profile.isPremium + ". Nickname: " + nicknameText;

console.log(summary);
Output✓ Tested · Node 24
Jordan is 31 years old. Premium: true. Nickname: No nickname set

This small example uses all five core values in a realistic way. It stores text with String, math-friendly data with Number, a decision with Boolean, and optional state with null. If nickname were missing entirely, it would be undefined instead.

10. Key Points

  • Values are the data your program uses, and types describe what those values are.
  • Number, String, and Boolean are the most common everyday types.
  • null means an intentional empty value.
  • undefined usually means a value was not assigned or not provided.
  • JavaScript may convert types automatically, so compare and convert carefully.
  • typeof is useful, but remember the special case of null.

11. Practice Exercise

Use this exercise to check whether you can recognize each basic type and handle missing values correctly.

  • Create four variables: one Number, one String, one Boolean, and one null value.
  • Write a function that accepts a value and prints its type using typeof.
  • Make sure the function treats null as a special case.
  • Print a message when a variable is still undefined.

Expected output: Your program should identify the types correctly, show that null is a special case, and report when a value has not been assigned.

Hint: Check value === null before relying on typeof, and use value === undefined to detect missing assignment.

Show solution
JavaScript
const count = 7;
const message = "Hello";
const isReady = false;
const emptyValue = null;
let missingValue;

function describeValue(value) {
  if (value === null) {
    console.log("This value is null.");
    return;
  }

  console.log("Type:", typeof value);
}

describeValue(count);
describeValue(message);
describeValue(isReady);
describeValue(emptyValue);

if (missingValue === undefined) {
  console.log("missingValue has not been assigned yet.");
}
Output✓ Tested · Node 24
Type: number
Type: string
Type: boolean
This value is null.
missingValue has not been assigned yet.

12. Final Summary

JavaScript values and types are the foundation of everyday coding. Number, String, and Boolean cover most of the data you manipulate, while null and undefined help you represent missing or intentionally empty values.

The most important habit is to be explicit about what kind of value you have and what kind of value you expect. That means converting when necessary, comparing carefully, and not assuming that every missing value means the same thing.

Once these basic types feel natural, the rest of JavaScript becomes much easier to reason about. A good next step is to learn about truthy and falsy values, because they build directly on the ideas in this article.