Skip to content

Reference data types in JavaScript

  • by

Reference data types in JavaScript are objects that are not primitive data types but are stored in memory as a reference to their location, rather than as the actual value.

JavaScript Reference data types include:

  1. Objects: Objects are used to store collections of key-value pairs, where the keys are strings and the values can be any data type, including other objects.
  2. Arrays: Arrays are also objects in JavaScript, but they are a special type of object used to store an ordered list of values.
  3. Functions: Functions are a special type of object used to define a set of instructions that can be called repeatedly.
  4. Dates: Dates are objects that represent a specific moment in time. They are commonly used in JavaScript to perform date and time calculations.
  5. RegExps: RegExps are objects that represent regular expressions, which are patterns used to match character combinations in strings.
  6. Maps and Sets: Maps and Sets are specialized objects used to store collections of data in unique ways. Maps store key-value pairs where keys can be any data type, while Sets store only unique values.

Note: The reference data types are mutable, which means that their values can be changed even after they have been created. This is different from primitive data types in JavaScript, such as numbers and strings, which are immutable.

Reference data types in JavaScript example

Simple example code of how to create and use reference data types in JavaScript:

Objects

<!DOCTYPE html>
<html>
  <body>    
    <script>
    // Object literal
    const person = { 
        name: "John", 
        age: 30, 
        hobbies: ["reading", "hiking", "traveling"] 
    };

    // Constructor
    const car = new Object();
    car.make = "Honda";
    car.model = "Civic";
    car.year = 2022;

    console.log(car)

    </script>
  </body>
</html>

Output:

Reference data types in JavaScript

Arrays

// Array literal
const numbers = [1, 2, 3, 4, 5];

// Constructor
const fruits = new Array("apple", "banana", "orange");
fruits.push("mango");

Functions:

// Function declaration
function add(a, b) {
  return a + b;
}

// Function expression
const subtract = function(a, b) {
  return a - b;
}

// Arrow function
const multiply = (a, b) => a * b;

Dates:

const today = new Date();
const tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);

Regular expressions:

const regex = new RegExp("hello", "gi");
const str = "Hello world!";
const matches = str.match(regex); // ["Hello"]

Maps and Sets:

const map = new Map();
map.set("name", "John");
map.set("age", 30);

const set = new Set([1, 2, 3, 4, 5]);
set.add(6);

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

Your email address will not be published. Required fields are marked *