JavaScript Non-primitive data types are derived from primitive data types and its also called reference types. These types of values are not stored directly in variables but rather are referenced by a pointer to a memory location where the value is stored.
Here is a list of Non-primitive data types in JS:
- Objects: a collection of key-value pairs. They can contain any type of value, including other objects, functions, and arrays.
- Arrays: are ordered collections of values. They can contain any type of value, including other arrays and objects.
- Functions: are objects that can be called to perform a specific task. They can be passed as arguments to other functions, returned from functions, and stored as variables.
- Dates: are objects that represent a specific date and time.
- Regular expressions: are objects that are used to match patterns in strings.
- Maps: are objects that allow you to store key-value pairs, where both the keys and values can be any type of value.
- Sets: are objects that allow you to store unique values of any type.
- Promises: are objects that represent a value that may not be available yet, but will be resolved in the future.
- Symbols: Symbols are unique, immutable values that can be used as property keys in objects.
Note: The non-primitive data types are passed by reference, whereas primitive data types are passed by value.
Non-primitive data types in JavaScript example
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
// Objects
let person = { name: 'John', age: 30, occupation: 'Developer' };
console.log(person)
// Arrays
let numbers = [1, 2, 3, 4, 5];
console.log(numbers)
// Functions
function addNumbers(num1, num2) {
return num1 + num2;
}
console.log(addNumbers(1,2))
// Dates
let today = new Date();
console.log(today)
// Regular expressions:
let regex = /hello/gi;
console.log(regex)
// Maps
let myMap = new Map();
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
console.log(myMap)
// Sets
let mySet = new Set();
mySet.add('value1');
mySet.add('value2');
console.log(mySet)
// Promises
let myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Resolved!');
}, 2000);
});
console.log(myPromise)
// Symbols
let mySymbol = Symbol('mySymbol');
console.log(mySymbol)
</script>
</body>
</html>
Output:
Comment if you have any doubts or suggestions on this Js data type topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version