In JavaScript, composite types (also known as non-primitive types) are objects used to store collections of data or more complex entities. They can hold multiple values and are mutable. Here are the main composite types in JavaScript:
1. Object
- A collection of key-value pairs.
- Values can be of any type, including other objects.
- Example:
let person = { firstName: "John", lastName: "Doe", age: 30 };
2. Array
- A special type of object used to store ordered lists of values.
- Values can be accessed by their index.
- Example:
let fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits[0]); // "Apple"
3. Function
- A block of code designed to perform a particular task and is an object in JavaScript.
- Functions can be assigned to variables, passed as arguments, and returned from other functions.
- Example:
function greet(name) { return "Hello, " + name; } console.log(greet("John")); // "Hello, John"
4. Date
- Represents a date and time.
- Example:
let date = new Date(); console.log(date); // Current date and time
5. RegExp (Regular Expression)
- Represents a regular expression, used for pattern matching within strings.
- Example:
let pattern = /google/i;
6. Map
- A collection of key-value pairs where keys can be of any type.
- Example:
let map = new Map(); map.set("name", "John"); map.set("age", 30);
7. Set
- A collection of unique values.
- Example:
let set = new Set(); set.add("Apple"); set.add("Banana");
Characteristics of Composite Types:
- Mutable: Their values can be changed after creation.
- Stored by Reference: When assigned or passed, they reference the same memory location.
Understanding composite types is essential for working with complex data structures and functionality in JavaScript.