Non-Primitive (Reference) Data Types in JavaScript

JavaScript2 min read
Non-Primitive (Reference) Data Types in JavaScript
javascriptnon-premitive data typesdata types

Non-primitive data types in JavaScript are not directly stored in variables but are stored as references to objects in memory. These types are mutable, meaning their values can be modified after they are created.

After discussing primitive data types, let's explore non-primitive or reference data types in JavaScript.

1. Non-Primitive Data Types Overview

Non-primitive data types in JavaScript are not directly stored in variables but are stored as references to objects in memory. These types are mutable, meaning their values can be modified after they are created.

Types of Non-Primitive Data in JavaScript:

Object Type

  • The object type represents a collection of key-value pairs.
  • Objects in JavaScript can store any type of data, including numbers, strings, arrays, and functions.
let person = { name: "John", age: 30 }; document.write(person.name); // Output: John
  • Explanation: - In this example, the object person has two properties: name and age.

Array Type

  • An array is a type of object that stores an ordered collection of elements (values), which can be accessed by their index.
let numbers = [10, 20, 30]; document.write(numbers[1]); // Output: 20
  • Explanation: - The array numbers stores three values. The value at index 1 is 20.

Map Type

  • A map is a built-in object that allows the storage of key-value pairs, where keys can be of any type (unlike object keys, which must be strings or symbols).
let map = new Map(); map.set('name', 'Alice'); map.set(1, 'one'); document.write(map.get('name')); // Output: Alice
  • Explanation: - In this map, both a string and a number are used as keys.

Function Data Type

  • A function is a block of reusable code that can be called to perform specific tasks. Functions in JavaScript can also be stored in variables or passed as arguments.
function greet() { console.log("Hello, World!"); } greet(); // Output: Hello, World!
  • Explanation: - The function greet is a reusable block of code that prints a message when called.

Summary:

  • Non-primitive data types include objects, arrays, maps, and functions.
  • These types are mutable, meaning they can be modified after they are created.
  • Objects store key-value pairs, arrays store ordered collections, maps store key-value pairs with any type of key, and functions allow for reusable blocks of code.