Primitive and Reference Data Types in Js

In JavaScript, data types can be broadly categorized into primitive data types and reference data types. Let's explor primitive and reference data types:

Primitive Data Types

Primitive data types are basic building blocks in JavaScript, representing single values. They are immutable, meaning their values cannot be changed after they are created. Here are the main primitive data types in JavaScript:

1. Number: Represents numeric values, including integers and floating-point numbers.

var num = 42;

2. String: Represents sequences of characters enclosed in single ('') or double ("") quotes.

var name = "John";

3. Boolean: Represents true or false values.

var isTrue = true;

4. Undefined: Represents a variable that has been declared but hasn't been assigned a value.

var undefinedVar;

5. Null: Represents the intentional absence of any value or object.

var noValue = null;

6. Symbol: Represents unique and immutable values, often used as object property keys.

var symbol = Symbol("unique");

7. BigInt: Represents large integers, useful for working with very large numbers.

var bigInt = 1234567890123456789012345678901234567890n;

Reference Data Types

Reference data types, also known as objects, are more complex data structures that can hold multiple values and methods. They are stored by reference, meaning the variable contains a reference to the memory location where the data is stored, rather than the actual data itself. Here are some common reference data types:

1. Object: Represents a collection of key-value pairs, where keys are strings (or Symbols) and values can be of any data type.

Example:

var person = {
    firstName: "Alice",
    lastName: "Johnson",
    age: 30
};

2. Array: Represents an ordered list of values, accessible by their numeric index.

Example:

var numbers = [1, 2, 3, 4, 5];

3. Function: Represents a reusable block of code that can be executed.

Example:

function greet(name) {
    console.log("Hello, " + name + "!");
}

4. Date: Represents a specific moment in time.

Example:

var currentDate = new Date();

5. RegExp: Represents regular expressions used for pattern matching in strings.

Example:

var pattern = /abc/;

6. Other Built-in Objects: JavaScript provides many other built-in objects like Map, Set, Promise, and more, each with their specific use cases.

Reference data types can be more complex and versatile compared to primitive types. They allow you to create and manipulate more intricate data structures and encapsulate behavior along with data.

Understanding the distinction between primitive and reference data types is crucial for efficient memory management and effective programming in JavaScript.