Skip to content

Non-primitive data types in JavaScript

  • by

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:

  1. Objects: a collection of key-value pairs. They can contain any type of value, including other objects, functions, and arrays.
  2. Arrays: are ordered collections of values. They can contain any type of value, including other arrays and objects.
  3. 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.
  4. Dates: are objects that represent a specific date and time.
  5. Regular expressions: are objects that are used to match patterns in strings.
  6. Maps: are objects that allow you to store key-value pairs, where both the keys and values can be any type of value.
  7. Sets: are objects that allow you to store unique values of any type.
  8. Promises: are objects that represent a value that may not be available yet, but will be resolved in the future.
  9. 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:

Non-primitive data types in JavaScript

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading