# Understanding Different Data Types: A Comprehensive Guide

Data type refers to the type of data that a JavaScript variable can hold.

Assigning values to variables, including numbers, text, and true or false, has been all we've done up to this point. What are all of those things, and what are our various options? In JavaScript, these are known as Types.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678284422349/217c5565-3f03-4998-8b85-03ec4d4dde44.png align="center")

There are eight data types in JavaScript i.e. seven primitive (Number, BigInt, String, Boolean, Null, Undefined and Symbol) and one non-primitive(Object)

# Primitive Data Types

Except for Objects, all types specify immutable values that are explicitly expressed at the lowest level of the language. Values of these categories are referred to as primitive values.

# ⚡**Numbers**

Both integer and float, which is a decimal number, are represented by the number type.

```jsx
let a = 20; //interger
let b = 10.2; //float
```

> 📝 **Note:** The JavaScript engine simply ignores `_` between digits.
> 
> ---
> 
> Suppose, we need to write 1 billion. The obvious way is:
> 
> ```jsx
> let billion = 1000000000;
> ```
> 
> underscore `_` as can be used as a separator:
> 
> ```jsx
> let billion = 1_000_000_000;
> ```
> 
> By adding the letter `e` to a number and specifying the number of zeroes, we can shorten it:
> 
> ```jsx
> let billion = 1e9;  // 1 billion, literally: 1 and 9 zeroes
> let b =  1.5e9;  // same as 1500000000 or 1_500_000_000
> ```
> 
> > So we can say, `e` multiplies the number by `1` with the specified number of zeroes.
> > 
> > ```jsx
> > 6e3 === 6 * 1000; // e3 means *1000
> > ```
> > 
> > A negative number after `"e"` represents division by 1 with the zeroes count.
> > 
> > ```jsx
> > 
> > 6e-3 === 6 / 1000; // -3 divides by 1 with 3 zeroes
> > ```

There are many operations for numbers, e.g. multiplication `*`, division `/`, addition `+`, subtraction `-`, and so on.

This data type also includes so-called "special numeric values : `Infinity`, `-Infinity` and `NaN`.

* `Infinity` represents the mathematical Infinity ∞. It is a special value that’s bigger than any integer.
    

We can get it as a result of division by zero:

```jsx
alert( 1 / 0 ); // Infinity
```

Or just reference it directly:

```jsx
alert( Infinity ); // Infinity
```

* `NaN` represents a computational error. It is the outcome of a flawed or undefined mathematical operation such as:
    

```jsx
alert( "This is not a number" / 2 ); // NaN
```

> **📝 Note:** Any further mathematical operation on `NaN` returns `NaN`:
> 
> ---
> 
> ```jsx
> alert( NaN + 1 ); // NaN
> alert( 2 * NaN ); // NaN
> ```
> 
> There is just one exception to that: `NaN * 0` is `1`.

## **Helper Methods**

There are four Helper Methods that you are most likely to use.

1. `Math.round()`\- The number you provided in will be returned to you, either rounded up or down depending on the value.
    
2. `Math.floor()`\- It will give you the lower end of that number.
    
3. `Math.ceil()`\- This will give you the upper number.
    
4. `Math.random()`\- This will give you a random number every time between 0 and 1.
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678284254585/5030ac61-24b3-46e7-888d-60add9dcc41b.png align="center")
    

## **Modulo and Power Operators**

We have two more operators, known as the modulo and the power, in addition to multiplication, division, addition, subtraction, and addition.

### M**odulus**

The **modulus** operator (`%`) returns the remainder after division. ( `number1 % number2 = Remainder`).

```jsx
// 5 mod 2 = 1
5 % 2 = 1 // 1 is remainder when 5 is divided by 2

// 10 mod 2 = 0
10 % 2 = 0 //0 is remainder when 10 is divided by 2
```

### Exponentiation

The first operand is raised to the second operand's power by using the exponentiation `(**)` operator to return the result. It is equivalent to `Math.pow()`, except that BigInts are also accepted as operands.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678284222614/191f7aff-f9ce-47e2-943c-1675004072d6.png align="center")

> **📝 Math.pow()**
> 
> The `Math.pow(x,y)` method returns the value of `x` raised to the power `y`.
> 
> That is: `Math.pow(x,y) = x^y`
> 
> ```jsx
> Math.pow(5, 3); // output: 125
> Math.pow(4, 0.5); // output: 2
> Math.pow(-5, 0.5); // output: NaN
> ```

---

# ⚡BigInt

The "number" type in JavaScript cannot represent integer numbers that are more than `(2^53^-1)` (which equals `9007199254740991`) or smaller than `-(2^53^-1)` for negative values.

> The `±(2^53^-1)` range is sufficient for the majority of uses, but there are instances when we require the complete range of really large numbers, such as when using encryption or microsecond-accurate timestamps.
> 
> `BigInt` numbers are rarely needed.

An integer is transformed into a BigInt value by adding n to the end of it:

```jsx
// the "n" represents that it's a BigInt
const bigInt = 1234567890123456789012345678901234567890n;
```

---

# ⚡String

The `string` type represents textual data and must be surrounded by quotes.

In JavaScript, there are 3 types of quotes.

```jsx
let str = "Hola";                         // 1.Double quotes: ""
let str2 = 'Single quotes';               // 2.Single quotes: ''
let phrase = `embed another ${str} here`; // 3.Backticks: ``
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678300496702/3279bfb9-ff1b-401e-92f0-e10530888f79.png align="center")

Both single and double quotes are identical.

Backticks are “extended functionality” quotes. They allow us to embed variables and expressions into a string by wrapping them in `${…}` , for example:

```jsx
let name = "Robin";

// embed a variable
alert( `Hello,${name}!` ); // Hello, Robin!

// embed an expression
alert( `the result is${1 + 2}` ); // the result is 3
```

The expression inside `${…}` is evaluated and the result becomes a part of the string. We can put anything in there: a variable like `name` or an arithmetical expression like `1 + 2` or something more complex.

Backticks offer the benefit of enabling a string to extend over multiple lines.

```jsx
let studentsList = `Students:
 1. Barry
 2. Clark
 3. Bruce
`;

alert(studentsList); // students list
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678300441095/b6eb9fcb-7cbf-4a66-9cb9-f9c78ef7b9e1.png align="center")

## **Putting String on Multiple Lines**

Single and double quotes can still be used to separate several lines of text when using the "newline character," denoted as `\n`, which represents a line break:

```jsx
let studentsList = "Students:\n 1. Barry\n 2. Clark\n 3. Bruce\n";

alert(studentsList); // students list
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678374984762/59b228f6-08c5-47cb-b312-5854720c714e.png align="center")

## **String length**

The `length` property has the string length:

```jsx
let i = `Hi\\n`
i.length // 3

'Robin'.length // 3
```

Here, `\n` is a single “special” character, so the length of the string is `3`.

## Accessing characters

Use square brackets `[pos]` or the method [`str.at`](http://str.at)`(pos)` to obtain a character at position pos, beginning with the first character at position zero.

```jsx
let str = `Hola`;

// first character
str[0];    // H
str.at(0); // H

// last character
str[str.length - 1]; // a
str.at(-1);          // a
```

## Strings are immutable

JavaScript does not allow for the modification of strings, making it impossible to alter individual characters.

```jsx
let str = 'Hi';
alert( str[0] ); // H

str[0] = 'h';
alert( str[0] ); // H
```

## Changing the case

Methods toLowerCase() and toUpperCase() change the case:

```jsx
'Sahil'.toUpperCase(); // SAHIL
'Sahil'.toLowerCase(); // sahil

let name = 'Sanji';
name.toUpperCase();   // SANJI
```

Or, if we want a single character lowercased

```jsx
'Robin'[0].toLowerCase() // 'r'
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678386132081/8e7e159d-0c17-40cb-8a71-53252c16da61.png align="center")

## Searching for a substring

The method is str.indexOf(substr, pos).

Starting at position pos, it searches for the substr in `str` and returns either the location where the match was found or `-1` if none was found.

For instance:

```jsx
let str = 'Javascript is fun';

str.indexOf('Javascript'); // 0, because 'Javascript' is found at the beginning

str.indexOf('javascript'); // -1, not found, the search is case-sensitive

str.indexOf("fu");         // 14, "fu" is found at the position 14 (Javascript is fun)
```

The optional second parameter allows us to start searching from a given position.

```jsx
str.indexOf("fu",15); // -1, it started searching from 15th character
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678387363275/2b1291d5-7c4a-45f4-b21c-5f9ed3241c4a.png align="center")

## Getting a substring

The portion of the string from start to end (but excluding end) is returned by the function `str.slice(start [, end])`.

For example:

```jsx
let str = "Pirates";

str.slice(0, 5); // 'Pirate', substring from 0 to 6 (not including 6 's')

str.slice(0, 1); // 'P', from 0 to 1, (not including 1), so only character at 0 is returned
```

`slice` continues till the end of the string if the second parameter is absent:

```jsx
let str = "Pirates";
str.slice(2); // 'rates', from the 2nd position till the last position
```

`start/end` can also have negative values. These imply that the position is counted starting from the string's end

```jsx
let str = "Pirates";

// start at the 6th position from the right, end at the 1st from the right
str.slice(-6, -1); // 'irate'
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678434006698/8279cf7c-2005-4d02-bc41-97ded49791cb.png align="center")

## Concatenation and Interpolation

Concatenation and interpolation are advantages of backticks.

* When two or more strings are combined into one, this is known as **concatenation**.
    
* When you insert a variable inside of a string, this is called **interpolation**.
    

Let’s see how we can achieve these without backticks.

For instance:

```jsx
const greet = "Hola! my name is. Nice to meet you";
```

If we wanted to add our name to the end of the "Hola! my name is." sentence.

Previously, you had to close single and double quotes, add a plus sign (which acts as concatenation), then your variable or string, followed by another plus sign.

```jsx
const greet = "Hola! my name is " + name + ". Nice to meet you."; 
// name is already defined
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678435419786/ce7ca790-bd0e-45bc-9a87-3a5fea9a6e7e.png align="center")

This approach to interpolation is not great at all, that’s why backticks are introduced.

In JavaScript, the `+` symbol has two purposes. It performs concatenation when used with a string. But you can also add numbers with it.

---

# ⚡Boolean

The only possible values for the boolean type are `true` and `false`.

`true` denotes "yes, correct," and `false` denotes "no, wrong" in the yes/no values that are often stored using this type.

For example:

```jsx
let isChecked = true; // yes, it is checked
```

Boolean values also come as a result of comparisons:

```jsx
let isGreater = 2 > 1;

isGreater; // true (the comparison result is "yes")
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678720374714/d604faf4-a725-40d4-aa0e-b419d6acd983.png align="center")

### Equality (Equal, Double Equal, Triple equal )

Let's first focus on equality.

* To give a variable a value, use the equal symbol `=`.
    

```jsx
const age = 20;
```

* Triple equals `===` should nearly always be used instead of double equals `==`.
    

Although there are a few exceptions when double equals can be used, triple equals are nearly always preferable.

Let's take the age variable in the console and do the following

* `age === 20` will return true
    
* `age === 10` will return false
    

Let's take another variable

```jsx
const age2 = 20;

age === age2; // true
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678721318848/87ce2614-9e61-4d24-ad31-b9d27cbfc3e4.png align="center")

There, the browser is making sure that the first variable's value and the second variable's value are the same by verifying the values of both variables.

What would happen if instead, we did `20 == 20`, with a double equal? It would return true.

What would happen if we used a double equals `20 == 20`, instead of `20 === 20`? It would be true.

Why are there two separate methods for checking equality?

Triple equal verifies that both the types and values of the items on the left and the right are the same.

**So,** **Triple equals will always check for both value and type.**

Now, If we did `"20" == 20`, what would happen?

`true` would be displayed on the console. Why?

Because the value is the same, but the types are not.

And If we did `"20" === 20`, it would display false.

This is because triple equal checks for if the values are equal or not as well as if the types are equal or not. In the above example, `"20"` was string type whereas the value on the right-hand side was number type.

## **Logical operators**

There are three basic logical operators in JavaScript: `||` (OR), `&&` (AND), `!` (NOT).

While they are referred to as "logical," they are not limited to boolean values and may be applied to values of any type. Thus, any kind of outcome is possible.

1. ### **|| (OR)**
    

* Two vertical line symbols serve as the "OR" operator's representations:
    
    `result = a || b;`
    
* It returns `true` if any of its arguments are `true` and `false` otherwise.
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678729775384/aa4ab6af-f5bf-49c0-81de-bc9797ad258b.png align="center")
    
    As we can see, the outcome is always true unless both operands are false in which case it is false.
    
    > **📝NOTE:** An operand is transformed into a boolean for evaluation if it is not already one.
    
    We can pass more than two conditions as well:
    
    ```jsx
    let hour = 11;
    let isHoliday = true;
    
    if (hour < 10 || hour > 18 || isHoliday) {
      alert( 'Plan a trip.' );
    }
    ```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678730232963/ec972a05-764b-47fd-b76d-ff7461b62ea8.png align="center")
    
    1. ### **&& (AND)**
        
    
    * Two ampersands `&&` are used to denote the AND operator.
        
        `result = a && b;`
        
    * If both operands are `true`, AND returns `true`. Otherwise, it returns `false`.
        
        ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678730497353/8d66f822-d8fb-4178-83c1-2407b7c92ce1.png align="center")
        
        1. ### **! (NOT)**
            
        
        * The exclamation mark `!` is used to indicate the boolean NOT operator.
            
            `result = !value;`
            
        * It accepts a single argument and converts the operand to a boolean type: `true/false` and returns the inverse value.
            
        
        For example:
        
        ```jsx
        !true ; // false
        !0 ; // true
        ```
        
        > **📝NOTE:** NOT `!` has the greatest precedence of all logical operators, it is always executed before `&&` or `||`.
        

---

# ⚡null

* The unique `null` value does not fit into any of the aforementioned types.
    
* It creates a unique type on its own that only has the `null` value
    
    `let age = null;`
    
* It only serves as a special value that stands in for "nothing," "empty," or "value unknown”.
    

---

# ⚡undefined

* The value `undefined` is also distinct from other types. Similar to `null`, it creates its own type.-
    
* `undefined` simply means that a value has not been assigned.
    
* Whenever a variable is created but not assigned, then its value is `undefined`
    
    JavaScript
    
    ```javascript
    let name;
    
    age; // shows "undefined"
    ```
    

---

# ⚡Symbols

I’ll cover it with Objects as it will be easier to understand as the `symbol` type is used to create unique identifiers for objects. We have to mention it here for the sake of completeness, but also postpone the details till we know the objects.

> ## typeof operator
> 
> The type of the operand is returned by the `typeof` operator. It comes in handy when we wish to handle values of various types in different ways or when we just want to make a fast check.
> 
> ```jsx
> typeof undefined // "undefined"
> 
> typeof 7 // "number"
> 
> typeof 10n // "bigint"
> 
> typeof true // "boolean"
> 
> typeof "Zoro" // "string"
> 
> typeof Symbol("id") // "symbol"
> 
> typeof null // "object"  (2)
> 
> typeof alert // "function"  (3)
> ```

Hope it helped you!

If you have any doubts or if I made some mistake comments it down.
