# 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.

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.

```
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:

`let billion = 1000000000;`

underscore

`_`

as can be used as a separator:

`let billion = 1_000_000_000;`

By adding the letter

`e`

to a number and specifying the number of zeroes, we can shorten it:

`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.

`6e3 === 6 * 1000; // e3 means *1000`

A negative number after

`"e"`

represents division by 1 with the zeroes count.

`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:

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

Or just reference it directly:

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

`NaN`

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

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

📝 Note:Any further mathematical operation on`NaN`

returns`NaN`

:

`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.

`Math.round()`

- The number you provided in will be returned to you, either rounded up or down depending on the value.`Math.floor()`

- It will give you the lower end of that number.`Math.ceil()`

- This will give you the upper number.`Math.random()`

- This will give you a random number every time between 0 and 1.

**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`

).

```
// 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.

📝 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`

`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:

```
// 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.

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

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:

```
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.

```
let studentsList = `Students:
1. Barry
2. Clark
3. Bruce
`;
alert(studentsList); // students list
```

**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:

```
let studentsList = "Students:\n 1. Barry\n 2. Clark\n 3. Bruce\n";
alert(studentsList); // students list
```

**String length**

The `length`

property has the string length:

```
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`

`(pos)`

to obtain a character at position pos, beginning with the first character at position zero.

```
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.

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

## Changing the case

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

```
'Sahil'.toUpperCase(); // SAHIL
'Sahil'.toLowerCase(); // sahil
let name = 'Sanji';
name.toUpperCase(); // SANJI
```

Or, if we want a single character lowercased

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

## 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:

```
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.

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

## 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:

```
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:

```
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

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

## 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:

```
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.

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

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:

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

Boolean values also come as a result of comparisons:

```
let isGreater = 2 > 1;
isGreater; // true (the comparison result is "yes")
```

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

Let's first focus on equality.

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

.

```
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

```
const age2 = 20;
age === age2; // true
```

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.

**|| (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.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:

`let hour = 11; let isHoliday = true; if (hour < 10 || hour > 18 || isHoliday) { alert( 'Plan a trip.' ); }`

**&& (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`

.**! (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:

```
!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

`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.

`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.

### Did you find this article valuable?

Support **Sahil Chandravanshi** by becoming a sponsor. Any amount is appreciated!