JavaScript Data Types
Tags: javascript, beginners, tutorial, programming
Published: 2024-04-02 07:14:52

## **1. Introduction**

Computer programs generally deal with a lot of data. This data can be one of several types. Each type has its own purpose, utilities, and underlying mechanism of implementation.

In this chapter, we shall get an overview of the data types that JavaScript comes equipped with, out of the box.

We'll understand the distinction between **primitive** and **object (non-primitive)** types before moving on to explore the six most common primitive types and the three most common object types. Moreover, we'll also consider the typeof operator, used to inpsect the type of a given value.

##**2. What are data types?**

A data type describes a set of values and the operations possible on those values.

JavaScript divides data essentially into two main categories: **primitives** and **objects (non-primitives)**.

<u>**2.1 Primitive data types**:</u>
Primitive data types in JavaScript are **predefined** and built-in data types. They are simple and represent fundamental values. The primitive data types in JavaScript include:

- **String**: Represents textual data and is enclosed in single quotes ('') or double quotes ("").
- **Number**: Represents numeric values, including integers and floating-point numbers.
- **BigInt**: Represents integers with arbitrary precision, allowing for the representation of extremely large numbers.
- **Boolean**: Represents a logical value, either true or false.
- **Undefined**: Represents a variable that has been declared but has not been assigned a value.
- **Null**: Represents the intentional absence of any object value.
- **Symbol**: Represents a unique and immutable value that can be used as an identifier for object properties.

<u>**2.2 Non-primitive data types**:</u>
On the other hand, **non-primitive** data types in JavaScript are derived from primitive data types. They are also known as reference data types or derived data types. Non-primitive data types include:

- **Object**: Represents a collection of key-value pairs and can hold complex data structures.
- **Array**: Represents an ordered list of values, accessible by their index.
- **Function**: Represents a reusable block of code that performs a specific task.
- **Date**: Represents a specific moment in time.
- **RegExp**: Represents a regular expression, used for pattern matching within strings.
- **Error**: Represents an error object that contains information about an error that occurred during the execution of code.

> The main difference between **primitive** and **non-primitive** data types is that primitive data types are **immutable**, meaning their values cannot be changed, while non-primitive data types are **mutable** and can be modified.


Let's understand what is mutable and immutable meaning?

<u>**2.3 Mutable :** </u>
Mutable objects or variables can be modified or changed after they are created. This means that their state or value can be altered without creating a new object. Examples of mutable objects in JavaScript include arrays and objects.

```
let mutableArray = [1, 2, 3];
mutableArray.push(4); // Modifying the array by adding an element
console.log(mutableArray); // Output: [1, 2, 3, 4]

let mutableObject = { name: "John", age: 25 };
mutableObject.age = 26; // Modifying the object by changing the age property
console.log(mutableObject); // Output: { name: "John", age: 26 }

```

<u>2.4 **Immutable**:</u>
 
Immutable objects or variables, on the other hand, cannot be changed once they are created. Any attempt to modify their value will result in the creation of a new object with the updated value, while the original object remains unchanged. Examples of immutable objects in JavaScript include strings and numbers.

```
let immutableString = "Hello";
let newString = immutableString.toUpperCase(); // Creating a new string with modified value
console.log(immutableString); // Output: "Hello"
console.log(newString); // Output: "HELLO"

let immutableNumber = 5;
let newNumber = immutableNumber + 1; // Creating a new number with modified value
console.log(immutableNumber); // Output: 5
console.log(newNumber); // Output: 6

```

> It's important to note that while primitive data types (such as strings and numbers) are immutable, objects (including arrays and custom objects) are mutable by default in JavaScript. However, you can use techniques like object freezing or immutability libraries to enforce immutability for objects if desired.

**<u>2.5 Dynamic and weak typing :</u>**
JavaScript is a dynamic language with dynamic types. Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned) values of all types:

```
let foo = 42; // foo is now a number
foo = "bar"; // foo is now a string
foo = true; // foo is now a boolean

```
JavaScript is also a weakly typed language, which means it allows implicit type conversion when an operation involves mismatched types, instead of throwing type errors.

```
const foo = 42; // foo is a number
const result = foo + "1"; // JavaScript coerces foo to a string, so it can be concatenated with the other operand
console.log(result); // 421

```
## **3. Primitive data types**

In JavaScript, primitive data types are the most basic data types provided by the language. They are used to represent simple values and are not objects. Here are the primitive data types in JavaScript:

**Number**: Represents numeric values, including integers and floating-point numbers. For example: 10, 3.14.

**String**: Represents a sequence of characters enclosed in single or double quotes. For example: 'Hello', "JavaScript".

**Boolean**: Represents a logical value, either true or false. It is often used for conditional statements and comparisons.

**Undefined**: Represents a variable that has been declared but has not been assigned a value. If a variable is declared without initialization, its value is undefined.

**Null**: Represents the intentional absence of any object value. It is often used to indicate that a variable has no value or that an object does not exist.

**Symbol**: Represents a unique identifier. Symbols are often used as keys in objects to avoid naming conflicts.

**BigInt**: Represents integers with arbitrary precision. It can be used to store and perform operations on large numbers that exceed the limits of the Number type.


These primitive data types are immutable, meaning their values cannot be changed once they are created. Additionally, they do not have any methods or properties associated with them.




![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/733mdw6ux6am76cjmku0.png)



To understand more about and deep in primitive data type follow the below...

[Full concept of Primitive data type](https://dev.to/imashwani/javascript-primitive-data-types-1l5)


## **4. Non-Primitive data types**

Non-primitive data types in JavaScript are derived from the primitive data types and are also known as reference data types or derived data types. These data types are stored in the **heap memory** of the system, unlike primitive data types which are stored in the **stack space of the system**.

In computer science, an object is a value in memory which is possibly referenced by an identifier. In JavaScript, objects are the only mutable values. Functions are, in fact, also objects with the additional capability of being callable.

**4.1 Array**

- JavaScript arrays are written with square brackets.
- Array items are separated by commas.
- An array is a special variable, which can hold more than one value.
- The following code declares (creates) an array called cars, containing three items (car names):

```
const cars = ["Saab", "Volvo", "BMW"];
```
> Array indexes are zero-based, which means the first item is [0], second is [1], and so on.

You can also create an array, and then provide the elements:

```
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
```

**Accessing Array Elements:**

You access an array element by referring to the **index** **number**:

```
const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
```

**4.2 Objects**

JavaScript objects are written with curly braces {}.
Objects are variables too. But objects can contain many values.
Object properties are written as **name:value** pairs, separated by **commas**.

```
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
```

> The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.

**Accessing Object Properties:**

You can access object properties in two ways:

```
objectName.propertyName
```
or

```
objectName["propertyName"]
```

**How is an array an 'object'?**

As we know, arrays fall in the object category of JavaScript data types i.e they are stored by **references** and NOT by their **actual values**.

> JavaScript simplifies the work of typeof by returning 'object' whenever the given expression is a reference to some data in memory.

An array is indeed a reference to an ordered bunch of data in memory and likewise translates to 'object' when inspected by the typeof operator.


## **5. Difference between primitive and non primitive datatypes**

**Note:-**
> It's important to note that non-primitive data types are stored in the **heap memory** of the system, while primitive data types are stored in **the stack space of the system**.

**Primitive Data Types:**


1. **Predefined**: Primitive data types are predefined (already defined) in JavaScript.
2. **Simple**: They are simple and basic data types.
3. **Immutable**: Primitive values are immutable, meaning they cannot be changed once created.
4. **Stored by Value**: Primitive values are stored directly in memory and accessed by their value.
5. **Examples**: Examples of primitive data types in JavaScript include numbers, strings, booleans, null, undefined, and symbols.


**Non-Primitive Data Types:**


1. **Created by the Programmer**: Non-primitive data types are created by the programmer and are not predefined in JavaScript (except for String).
2. **Complex**: They are more complex data types that can store collections or sets of data.
3. **Mutable**: Non-primitive values are mutable, meaning they can be modified after creation.
4. **Stored by Reference**: Non-primitive values are stored in memory as references and accessed by their reference.
5. **Examples**: Examples of non-primitive data types in JavaScript include objects, arrays, functions, and regular expressions.