What are the various data types in JavaScript?
JavaScript has a variety of data types that are categorized into two groups: primitive and non-primitive (complex) types.
Primitive Data Types
These data types are immutable and stored by value.
-
Number Represents both integer and floating-point numbers.
let age = 30; let price = 19.99;
-
String Represents a sequence of characters.
let name = 'Alice';
-
Boolean Represents a logical value:
true
orfalse
.let isValid = true;
-
Undefined A variable that has been declared but not assigned a value.
let x; console.log(x); // undefined
-
Null Represents an explicitly empty or non-existent value.
let y = null;
-
BigInt (ES2020) Represents integers with arbitrary precision.
let largeNumber = 123456789012345678901234567890n;
-
Symbol (ES2015) Represents a unique and immutable identifier.
let sym = Symbol('unique');
Non-Primitive (Complex) Data Types
These are mutable and stored by reference.
-
Object Used to store collections of key-value pairs or more complex entities.
let person = { name: 'Alice', age: 30 };
-
Array (a special type of Object) Represents an ordered list of values.
let fruits = ['apple', 'banana', 'cherry'];
-
Function (a callable Object) Represents executable code.
function greet() { return 'Hello!'; }
-
Date (built-in Object) Represents dates and times.
let now = new Date();
-
Other Built-in Objects Examples include
Map
,Set
,WeakMap
, andWeakSet
for specialized data structures.
Dynamic Typing
JavaScript is dynamically typed, meaning variables can hold any data type and change type at runtime.
let data = 42; // Number
data = 'Hello'; // Now a String
Conclusion
Understanding JavaScript's data types is essential for writing robust and bug-free code. Knowing their characteristics, such as mutability and storage, helps developers manage memory and avoid common pitfalls.