Question

12.

What are Non-Primitive Data Types in JavaScript

Answer

In JavaScript, non-primitive data types refer to types that are not one of the primitive types (Undefined, Null, Boolean, Number, BigInt, String, Symbol). These types can hold collections of values and more complex entities. The main non-primitive data type in JavaScript is the Object. Here's a brief overview:

Object

An Object is a collection of properties, where each property is defined as a key-value pair. Properties can be values of any type, including other objects, which allows for building complex data structures. Objects in JavaScript are mutable, meaning their properties can be altered.

let person = {
    firstName: "John",
    lastName: "Doe",
    age: 30
};

Objects can also represent more specific non-primitive structures, such as:

  • Arrays: Used to store multiple values in a single variable. Arrays are objects with integer-based keys and a length property.

    let fruits = ["Apple", "Banana", "Cherry"];
  • Functions: In JavaScript, functions are first-class objects, meaning they can have properties and methods just like any other object. Functions can be passed as arguments to other functions, returned as values from functions, and assigned to variables.

    function greet() {
        console.log("Hello, world!");
    }
  • Date: Used to work with dates and times.

    let now = new Date();
    console.log(now);
  • RegExp (Regular Expressions): Used for pattern matching and pattern search and replace functions on text.

    let re = /ab+c/;

Distinction from Primitive Types

The key distinctions between primitive and non-primitive data types are:

  1. Mutability: Non-primitive types (objects) are mutable, whereas primitive types are immutable. When you change the value of a primitive type, you are creating a new value in memory. In contrast, when you modify an object, you are changing its properties or contents, not creating a new object (unless you explicitly do so).

  2. Comparison: Primitive types are compared by their value, while non-primitive types are compared by their reference in memory. This means that two objects with identical properties are not equal because they are not the same object in memory.

    let a = {value: 1};
    let b = {value: 1};
    console.log(a === b); // false, because they are different objects in memory
  3. Storage: Variables of primitive types directly contain their values, whereas variables of non-primitive types store references to their values. This distinction is crucial for understanding how data is passed to functions and manipulated within your program.

Support us ❤️

Buy Us A Coffee