In JavaScript, data types are categories of values that determine how data can be used and manipulated within a program. JavaScript is a dynamically typed language, meaning variables do not need to be declared with a specific type—they can hold any data type and can change type during execution.
Data Types in JavaScript
1. Primitive Data Types
These are immutable (cannot be modified) and represent a single value.
-
String
Represents a sequence of characters, enclosed in quotes (
' '
," "
, or\
). Example:
let name = "Ayodeji";
- Number Represents numeric values, including integers and floating-point numbers. Example:
let age = 25;
let height = 5.9;
-
Boolean
Represents one of two values:
true
orfalse
. Example:
let isStudent = true;
- Undefined Represents a variable that has been declared but not assigned a value. Example:
let x;
console.log(x); // undefined
- Null Represents an explicitly empty or non-existent value. Example:
let y = null;
- Symbol (ES6) Represents a unique identifier, primarily used for object properties to avoid name conflicts. Example:
let sym = Symbol("unique");
-
BigInt (ES2020)
Represents integers larger than the safe limit for
Number
. Example:
let bigIntValue = 123456789012345678901234567890n;
2. Non-Primitive (Complex) Data Types
These can store collections of values and are mutable.
- Object A collection of key-value pairs. Objects can represent more complex data structures. Example:
let person = { name: "Ayodeji", age: 25 };
- Array A special type of object used to store an ordered collection of items. Example:
let colors = ["red", "green", "blue"];
- Function A block of code designed to perform a specific task, which itself is a type of object. Example:
function greet() {
console.log("Hello!");
}
Type Checking
- Use the
typeof
operator to check the type of a value:
console.log(typeof "Ayodeji"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (quirk in JavaScript)
console.log(typeof { name: "Ayodeji" }); // "object"
console.log(typeof Symbol("id")); // "symbol"
Dynamic Typing
Variables can change types dynamically:
let value = 42; // Number
value = "Hello"; // Now a String
value = true; // Now a Boolean
Conclusion
Understanding JavaScript data types is fundamental for efficient coding, as it helps you choose the right operations, handle edge cases, and debug issues effectively.
Top comments (1)
Great work 👍