In JavaScript, data types refer to the classification or categorization of values that a variable can hold. JavaScript is a dynamically typed language, which means that you don't need to explicitly declare the data type of a variable; the interpreter determines the data type dynamically during runtime.
Here are the main data types in JavaScript:
-
Primitive Data Types:
- String: Represents textual data, e.g., "Hello, World!".
- Number: Represents numeric values, e.g., 42 or 3.14.
-
Boolean: Represents either
true or false
. - Undefined: Represents the absence of a value or an uninitialized variable.
- Null: Represents the intentional absence of any object value.
-
Special Values:
- NaN (Not a Number): Represents a value that is not a legal number.
- Infinity and -Infinity: Represent positive and negative infinity, respectively.
-
Composite Data Types:
- Object:Represents a collection of key-value pairs and is a fundamental building block in JavaScript.
- Array: Represents an ordered list of values and is a specialized type of object.
- Function: Represents a reusable set of statements.
-
Derived Data Types:
- RegExp (Regular Expression):Represents a pattern used for matching character combinations in strings.
- Date:Represents a specific point in time.
JavaScript is loosely typed, meaning that a variable can hold values of any type, and its type can be changed during runtime. For example, a variable initially assigned a number can later be assigned a string or another type of value.
Here's an example illustrating some of the data types in JavaScript:
// Primitive data types
let str = "Hello, World!"; // String
let num = 42; // Number
let isTrue = true; // Boolean
let undef; // Undefined
let n = null; // Null
// Composite data types
let obj = { key: "value" }; // Object
let arr = [1, 2, 3]; // Array
let func = function() {}; // Function
// Special values
let notANumber = NaN; // NaN
let positiveInfinity = Infinity; // Infinity
// Derived data types
let regex = /pattern/; // Regular Expression
let today = new Date(); // Date
Understanding these data types is crucial for working with variables and performing operations in JavaScript.