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 TYPE
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 or false.
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 = 1234567890;
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"];
• FUNTION
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 (0)