Data Types in JavaScript

🧠 Introduction to Data Types

In JavaScript, a data type determines the kind of value a variable can hold and what operations can be performed on it. Understanding data types is crucial for writing reliable and bug‑free code.

>>“Know your data types — it’s the foundation of solid JavaScript.” ✨

🔤 Primitive Data Types

JavaScript has seven built‑in primitive types. Primitives are immutable and compared by value.

TypeExampleDescription
String"Hello"Textual data
Number42Integer or floating‑point numbers
BooleantrueLogical value: true or false
NullnullIntentional absence of any object value
UndefinedundefinedVariable declared but not assigned
SymbolSymbol("id")Unique identifier
BigInt12345678901234567890nArbitrarily large integers

💻 Primitive Examples

Primitive Values

let name = "Alice";        // String
let score = 99.5;              // Number
let isActive = true;           // Boolean
let empty = null;              // Null
let missing;                   // Undefined
let id = Symbol("id");         // Symbol
let big = 9007199254740991n;   // BigInt

🛠️ Non‑Primitive Data Types

Non‑primitives are objects, arrays, functions, and other complex structures. They are stored and compared by reference.

  • Object: Key‑value pairs — { name: "Bob", age: 30 }
  • Array: Ordered list — [1, 2, 3]
  • Function: Callable block of code — function foo()
  • Date: Date & time — new Date()
  • RegExp: Regular expressions — /abc/i

🔍 Checking Types with typeof

Using typeof

console.log(typeof "Hello");      // "string"
console.log(typeof 123);          // "number"
console.log(typeof true);         // "boolean"
console.log(typeof null);         // "object"  // historical bug
console.log(typeof undefined);    // "undefined"
console.log(typeof Symbol());     // "symbol"
console.log(typeof 10n);          // "bigint"
console.log(typeof {});           // "object"
console.log(typeof []);           // "object"
console.log(typeof (()=>{}));     // "function"

Note

⚠️ typeof null returns "object" due to legacy reasons.

🔄 Type Conversion

JavaScript performs implicit (coercion) and explicit conversions. Be aware of unexpected results!

Explicit Conversion

String(123);          // "123"
Number("45");           // 45
Boolean(0);             // false
parseInt("100px", 10);  // 100

Note

📌 Avoid implicit coercion like 5 + "5" (results in "55"); prefer explicit when clarity matters.

🧠 Summary

JavaScript data types fall into primitive and non‑primitive categories. Mastering them helps you avoid bugs and write clearer code.

  • ✅ Remember the seven primitives: String, Number, Boolean, Null, Undefined, Symbol, BigInt
  • ✅ Use typeof to inspect types, but watch for null
  • ✅ Convert types explicitly for predictable behavior
  • ✅ Understand that objects, arrays, and functions are reference types

📚 Learn More

>>“Good code begins with knowing your types.” 🚀