Skip to main content
← Back to Blog
2026-02-21 · 6 min readWeb DevelopmentUpdated Oct 30, 2026

Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions

A practical guide to JavaScript data types and functions. Learn the seven primitives, why floating-point math surprises you, how object references lead to accidental mutation, how function declarations and arrow functions differ, and how to build a formatResponse helper that checks the type of its input before it uses it. The final example was run with Node.js 22.

Avnish Yadav
Avnish Yadav
Developer & Automation Builder
3 views
Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions

Strip away the frameworks and libraries, and a program comes down to two things: data and the logic that works on it. This guide is for developers who can write JavaScript but still get surprised by a null where an array should be, or a total that comes out as 0.30000000000000004. You'll learn how JavaScript stores its values, how functions receive them, and how to write a helper that copes with messy input.

This is part 4 of the Frontend & JavaScript Fundamentals series. It follows CSS architecture, from selectors to BEM.

Key takeaways

  • JavaScript has seven primitive types, and primitives are immutable. Everything else is an object.
  • A function that changes an object's properties changes the caller's object too. Copy with spread or structuredClone() instead.
  • Check the type of input before you use it: typeof, Array.isArray() and instanceof cover most cases.

Part 1: The raw materials (data types)

JavaScript is dynamically typed. You don't declare types, which speeds up prototyping. The cost is discipline: you have to know what data flows through your code.

1. Primitives: immutable values

A primitive is a value that is not an object and can't be changed. MDN lists seven primitive types: Null, Undefined, Boolean, Number, BigInt, String and Symbol. Every other value, including arrays and functions, is an object.

Strings

Strings hold text: messages, prompts, ids. Template literals let you insert values and span several lines.

const metric = "CPU Usage";
const serverId = "srv-01";

// Old way: string concatenation
const oldPrompt = "Analyze the logs for " + serverId + " regarding " + metric;

// Template literal
const prompt = `Analyze the logs for ${serverId} regarding ${metric}`;
// Multi-line text and inserted values are easier to read this way.

Numbers

MDN describes the Number type as a double-precision 64-bit IEEE 754 value. In other words, integers and decimals share one floating-point type. Some decimal fractions can't be stored exactly, so the result of simple math can be slightly off.

console.log(0.1 + 0.2);
// 0.30000000000000004 (floating-point rounding)

// Fix for display: round to two decimal places
const total = Math.round((0.1 + 0.2) * 100) / 100; // 0.3

For money, a common rule of thumb is to store whole cents as integers and format them only for display. Integers are exact up to Number.MAX_SAFE_INTEGER (2⁵³ − 1). For larger whole numbers, MDN points you to BigInt, written with an n suffix such as 10n.

Booleans, null and undefined

These control the flow of your logic. The difference between null and undefined matters when you parse API responses.

  • Undefined: the variable exists but hasn't been given a value. JavaScript uses it by default.
  • Null: an intentional absence of value. You, the developer, set it.
let config; // undefined (did you forget to load it?)
let userSettings = null; // null (loaded, but the user has no settings)

One quirk to remember: typeof null returns "object". MDN traces it to the first implementation of JavaScript, where null shared the type tag used for objects, and a proposed fix was rejected. Always check for null on its own.

2. Objects and arrays (reference types)

Many beginner bugs live here. A variable that holds an object really holds a reference to it. MDN's functions guide puts it this way: arguments are passed by value, but if a function changes an object's properties, that change is visible outside the function.

const agentConfig = {
  model: "small-model",
  retries: 3,
};

function upgradeModel(config) {
  config.model = "large-model";
}

upgradeModel(agentConfig);
console.log(agentConfig.model);
// Output: "large-model"
// The caller's object was changed. In a large codebase, this is hard to trace.

The fix: return a copy

function safelyUpgradeModel(config) {
  // Create a copy with the spread operator
  return { ...config, model: "large-model" };
}
// The original agentConfig stays untouched.

Spread makes a shallow copy. MDN notes that it copies one level deep, so nested objects are still shared. When you need a full deep copy of plain data, use structuredClone(value).

Part 2: The factory lines (functions)

Functions hold behavior. Modern JavaScript uses two main syntaxes, and they behave differently.

1. Function declarations

The traditional form. Function declarations are hoisted with their value, so you can call one before the line where it appears in the file.

function processData(payload) {
  if (!payload) return null;
  return JSON.stringify(payload);
}

2. Arrow functions

Arrow functions are usually stored in a const. That variable is in the temporal dead zone until its line runs, so calling it earlier throws a ReferenceError. MDN also notes that arrow functions don't have their own this. They use the this of the code around them, so they shouldn't be used as object methods. They are short, which makes them a good fit for callbacks such as .map() and .filter().

// Alternative to the declaration above, not both in one file
const processDataArrow = (payload) => {
  if (!payload) return null;
  return JSON.stringify(payload);
};

// Implicit return for one-liners (good for data transformations)
const getIds = (users) => users.map((user) => user.id);
Form Call before its line? Own this? Good for
Function declaration Yes (hoisted with its value) Yes, set by how it's called Named helpers, hoisted utilities
Arrow function in a const No (ReferenceError) No, uses the outer this Callbacks, short transformations

Part 3: Building reusable logic

Now combine types and functions into something practical. Many apps need a small helper that takes messy input and returns one standard shape.

You'll build a formatResponse function. It handles strings, arrays, objects, errors and missing values, and returns one object shape for a frontend or API.

The strategy

  1. Accept any input.
  2. Check its type with typeof, Array.isArray() and instanceof.
  3. Return a standard object.

typeof can't tell an array from an object, since both give "object". MDN recommends Array.isArray() for that check.

The implementation

/**
 * Standardizes API responses regardless of input type.
 * @param {*} input - The raw data to format
 * @returns {object} - Standardized response object
 */
const formatResponse = (input) => {
  // Default structure
  const response = {
    success: true,
    data: null,
    timestamp: new Date().toISOString(),
  };

  // 1. Handle errors
  if (input instanceof Error) {
    return { ...response, success: false, error: input.message };
  }

  // 2. Handle missing values (null and undefined)
  if (input === null || input === undefined) {
    return { ...response, success: false, error: "No data provided" };
  }

  // 3. Handle strings (simple messages)
  if (typeof input === "string") {
    return { ...response, data: { message: input } };
  }

  // 4. Handle arrays (lists of items)
  if (Array.isArray(input)) {
    return { ...response, count: input.length, data: input };
  }

  // 5. Handle objects (standard payloads)
  if (typeof input === "object") {
    return { ...response, data: input };
  }

  // 6. Numbers, booleans and other primitives
  return { ...response, data: { value: input } };
};

// --- TESTING THE HELPER ---

// Scenario A: a database returns a list of users
console.log(formatResponse(["User1", "User2"]));
/* Output:
{
  success: true,
  data: [ 'User1', 'User2' ],
  timestamp: '...',
  count: 2
}
*/

// Scenario B: the system throws an error
console.log(formatResponse(new Error("API Rate Limit Exceeded")));
/* Output:
{
  success: false,
  data: null,
  timestamp: '...',
  error: 'API Rate Limit Exceeded'
}
*/

// Scenario C: a count of zero is data, not "no data"
console.log(formatResponse(0).data); // { value: 0 }

This example was run with Node.js 22; the timestamps are shown as '...'.

The earlier version sent numbers and booleans to the "No data provided" branch, so a count of 0 came back as a failure. Checking for null and undefined explicitly fixes that.

Why this matters for automation

The example above uses type guards: checks such as typeof and instanceof that confirm what a value is before you use it. In an automation workflow, you often don't control the format of the data coming from upstream.

If you read input.message without checking that input is an object, your script crashes on null. If you treat a number like a string, your math breaks. A few checks at the edge of your code prevent both.

Next in the series, scope and closures explains how functions remember the variables around them.

Frequently asked questions

What are the primitive data types in JavaScript?

There are seven: string, number, bigint, boolean, undefined, symbol and null. MDN defines them as types whose values are immutable. Everything else, including arrays and functions, is an object.

Is JavaScript pass by value or pass by reference?

Arguments are passed by value. For an object, the value is a reference, so the function and the caller point at the same object. Reassigning the parameter doesn't affect the caller, but changing a property does.

Why does typeof null return "object"?

It's a bug from the first implementation of JavaScript. MDN explains that null shared the type tag used for objects, and a proposed fix was rejected. Check for null with value === null.

Does the spread operator make a deep copy?

No. Spread copies one level deep, so nested objects are still shared with the original. Use structuredClone() when you need a deep copy of plain data. It can't copy functions.

When should I use an arrow function instead of a function declaration?

Use arrow functions for callbacks and short transformations, where the outer this is what you want. Use function declarations or method syntax for object methods and for helpers you want to call before their definition.

Sources

Verified against the sources below on October 30, 2026. Products and docs change often: check the linked sources if something looks different.

  1. MDN: JavaScript data types and data structures
  2. MDN: Number
  3. MDN: typeof
  4. MDN: Array.isArray()
  5. MDN: Functions (guide)
  6. MDN: Spread syntax
  7. MDN: structuredClone()
  8. MDN: The structured clone algorithm
  9. MDN: Arrow function expressions
  10. MDN: Hoisting (glossary)
All 30 parts in this series
  1. Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
  2. Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
  3. Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
  4. Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
  5. Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
  6. Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
  7. Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
  8. Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
  9. Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
  10. Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
  11. Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
  12. Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
  13. Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
  14. Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
  15. Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
  16. Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
  17. Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
  18. Part 18Getting Started with React: Deconstructing JSX and Component Architecture
  19. Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
  20. Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
  21. Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
  22. Part 22React Architecture: Advanced Navigation and Data Flow Patterns
  23. Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
  24. Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
  25. Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
  26. Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
  27. Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
  28. Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
  29. Part 29Introduction to Micro Frontends: Building Scalable Architectures
  30. Part 30The Frontend Architecture: From Junior Developer to Tech Lead
Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.