DEV Community

Muhammad Rizwan Ashiq
Muhammad Rizwan Ashiq

Posted on

Data Type

What is a Data Type?

In programming, a data type is a classification or category of data that determines what kind of value a variable can hold, what operations can be performed on that value, and how the value is stored in memory. Data types determine the amount of memory that needs to be allocated to a variable or object.

Different programming languages support different data types, but most languages include a few basic data types such as numbers, strings, and booleans. More complex data types, such as arrays, objects, and classes, can also be defined in most programming languages.

Each data type has its own set of rules and limitations. For example, a number data type can be used to store numeric values, but not text values. Similarly, a string data type can be used to store text values, but not numeric values. The rules of a data type determine what operations can be performed on variables of that type, such as addition or concatenation for numbers and strings, respectively.

Data type in JS

In JavaScript, there are different data types:

  • number
  • string
  • boolean
  • null
  • undefined
  • object
  • symbol
  • function

It's worth noting that JavaScript is a dynamically typed language, which means that you do not need to specify the data type of a variable when you declare it. The data type of a variable is determined automatically at runtime based on the value assigned to it. For example:

let x = 5; // Here x is a number

x = "John"; // Here x is a string

x = true; // Here x is a boolean

x = undefined; // Here x is undefined

x = { name: "John", age: 30 }; // Here x is an object

x = [1, 2, 3, 4]; // Here x is an object
Enter fullscreen mode Exit fullscreen mode

You can see that the data type of the variable x changes as we assign different values to it.

Note: TypeScript is a superset of JavaScript, adds static typing to JavaScript. With TypeScript, you can specify the data type of variable when you declare it. For example:

```ts title="Static typing in TypeScript"
let x: number = 5; // Here x is a number

// This will error
x = "John"; // This will cause an error because x is a number




### Primitive and Non-Primitive Data Types

In JavaScript, there are two broad types of data types: primitive and non-primitive data types. Primitive data types are `number`, `string`, `boolean`, `null`, `undefined`, and `symbol`. Non-primitive data types are `object` and `function`. We will learn about them in detail in the next sections.

Let's take a look at each of these data types in detail.

## Number:

Numbers in JavaScript can be integers (like 42, -137, or 11321) or floating-point values (like 3.14). JavaScript does not have a separate data type for integers and floating-point values, so they are both stored as numbers. You can use arithmetic operators like `+`, `-`, `*`, `/`, or `%` to perform calculations with numbers.



```js
const x = 42; // Integer
const y = 3.14; // Float
const z = x + y; // z will be 45.14
const i = Infinity; // Special value representing infinity
Enter fullscreen mode Exit fullscreen mode

A number can also be a special value called NaN (not a number). This value is returned by mathematical operations that can't be performed, such as undefined + 1, Infinity / Infinity (infinity divided by infinity) or 0 / 0 (zero divided by zero).

const x = 0 / 0; // x will be NaN

const y = Infinity / Infinity; // y will be NaN

const z = 42 / "foo"; // z will be NaN
Enter fullscreen mode Exit fullscreen mode

What is NAN?
NaN is a special value that is not equal to anything, including itself. To check if a value is NaN, you must use the isNaN() function.

isNaN(NaN); // true
isNaN(42); // false
isNaN("Hello"); // true
Enter fullscreen mode Exit fullscreen mode

Number Methods

There are a few methods that number data types have. Let's take a look at them.

toString()

toString() method converts a number to a string.

const x = 42;
const y = x.toString(); // y will be "42"
Enter fullscreen mode Exit fullscreen mode

toFixed()

Converts a number to a string, keeping a specified number of decimals.

const x = 42.123;
const y = x.toFixed(2); // y will be "42.12"
Enter fullscreen mode Exit fullscreen mode

toExponential()

Converts a number to a string in exponential notation.

const x = 42.123;
const y = x.toExponential(2); // y will be "4.21e+1"
Enter fullscreen mode Exit fullscreen mode

toPrecision()

Converts a number to a string in exponential notation, with a specified length.

const x = 42.123;
const y = x.toPrecision(2); // y will be "4.2e+1"
Enter fullscreen mode Exit fullscreen mode

String:

Strings are sequences of characters, and they can be defined using single quotes '', double quotes "", or backticks ``. Strings can contain letters, numbers, and special characters.

`js
const name = "Rizwan";
const greeting = "Hello, " + name + "!"; // greeting will be "Hello, Rizwan!"

const x = 10;
const y = 20;
const message = The sum of x and y is ${x + y}.; // message will be "The sum of x and y is 30."
`

What is a Template Literal?

A template literal is a string defining method that allows embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification.

`js
const name = Rizwan;
const greeting = Hello, ${name}!; // greeting will be "Hello, Rizwan!"

const x = 10;
const y = 20;
const message = The sum of x and y is ${x + y}.; // message will be "The sum of x and y is 30."

const multiline = `This is a

multiline string.; // multiline will be "This is a\nmultiline string."
``

You can use the + operator to concatenate (join) two strings together. If you try to concatenate a number with a string, the number will be converted to a string.

`js
const x = 42;
const y = "Hello";

const z = x + y; // z will be "42Hello"
`

And if you try to concatenate a string number with a regular number, then there will be no conversion. The result will be a string.

`js
const x = "42";
const y = 10;

const z = x + y; // z will be "4210"
`

Interestingly if you try to subtract, multiply, or divide a string number from a regular number, then the result will be a number.

`js
const x = "42";
const y = 10;

const a = x - y; // a will be 32
const b = x * y; // b will be 420
const c = x / y; // c will be 4.2
`

String Methods and Properties

There are many methods available for strings.

length property

Returns the length of a string.

`js
const name = "Rizwan";
const length = name.length; // length will be 6
`

toUpperCase() method

Converts a string to uppercase.

`js
const name = "Rizwan";
const upper = name.toUpperCase(); // upper will be "RIZWAN"
`

toLowerCase() method

Converts a string to lowercase.

`js
const name = "Rizwan";
const lower = name.toLowerCase(); // lower will be "rizwan"
`

charAt() method

Returns the character at a specific index in a string.

`js
const name = "Rizwan";
const char = name.charAt(0); // char will be "R"
`

indexOf() method

Returns the index of the first occurrence of a substring in a string.

`js
const name = "Rizwan";
const index = name.indexOf("z"); // index will be 2
`

lastIndexOf() method

Returns the index of the last occurrence of a substring in a string.

`js
const name = "Rizwan";
const index = name.lastIndexOf("z"); // index will be 4
`

startsWith() method

Checks if a string starts with a specific substring.

`js
const name = "Rizwan";
const startsWith = name.startsWith("Riz"); // startsWith will be true
`

endsWith() method

Checks if a string ends with a specific substring.

`js
const name = "Rizwan";
const endsWith = name.endsWith("wan"); // endsWith will be true
`

includes() method

Checks if a string contains a specific substring.

`js
const name = "Rizwan";
const includes = name.includes("izw"); // includes will be true
`

slice() method

Extracts a part of a string

`js
const name = "Rizwan";
const slice = name.slice(1, 4); // slice will be "izw"
const slice2 = name.slice(-3); // slice2 will be "wan"
`

substring() method

Extracts a part of a string between two specified indices.

`js
const name = "Rizwan";
const substring = name.substring(1, 4); // substring will be "izw"
`

Difference between slice() and substring()

The slice() method can take negative indices, and can take indices greater than the length of the string. The substring() method can't take negative indices, and can't take indices greater than the length of the string.

split() method

Splits a string into an array of substrings using a specific separator.

`js
const name = "Rizwan";

const split = name.split(""); // split will be ["R", "i", "z", "w", "a", "n"]
const split2 = name.split("z"); // split2 will be ["Ri", "wan"]
`

trim() method

Removes whitespace from both ends of a string.

`js
const name = " Rizwan ";
const trimmed = name.trim(); // trimmed will be "Rizwan"
`

repeat() method

Repeats a string a specified number of times.

`js
const name = "Rizwan";
const repeated = name.repeat(3); // repeated will be "RizwanRizwanRizwan"
`

Boolean:

Booleans represent true or false values. They are often used in conjunction with conditional statements to determine the flow of a program. You can use comparison operators like ==, !=, >, <, >=, and <= to compare values and return a boolean result.

`js
const u = true; // Boolean representing true
const v = false; // Boolean representing false

const x = 10;
const y = 20;
const isGreater = x > y; // isGreater will be false

const password = "password";
const isCorrect = password == "password"; // isCorrect will be true
`

Null:

The null data type represents the absence of a value or a null reference. It is not the same as an empty string or a zero. You can assign the value null to a variable to indicate that it has no value.

`js
const x = null; // Null value
console.log(x); // Output: null
`

Undefined:

The undefined data type indicates that a variable has been declared, but it has not been assigned a value. If you try to access the value of a variable that has not been assigned a value, it will return undefined.

`js
let x;
console.log(x); // Output: undefined
`

Undefined is also the default value of a variable that has been declared, but not assigned a value. You can assign the value undefined to a variable to indicate that it has no value.

`js
let x = undefined;
console.log(x); // Output: undefined
`

null vs undefined

The null and undefined data types are similar in that they both represent the absence of a value. However, they are different in the following ways:

  • null is an assignment value. It can be assigned to a variable as a representation of no value i.e. let x = null.
  • undefined is a type itself (undefined) that is assigned to variables that have not been assigned a value i.e. let x;.

`js
let x; // x is undefined
let y = null; // y is null
`

Object:

The Object data type represents a complex data structure that can store a collection of key-value pairs. You can use objects to store data in a more organized and structured way. An object can store any type of data, including numbers, strings, booleans, arrays, and even other objects.

Here is an example of how you can create an object in JavaScript:

`js
const person = {
name: "Rizwan Ashiq",
age: 30,
isPakistani: true,
education: ["BS Information Technology", "MS Computer Science"],
dob: {
day: 10,
month: 7,
year: 1996,
},
};
`

In this example, person is an object with five properties: name, age, isPakistani, education, and dob. Each property has a key (a string) and a value (a number, a string, a boolean, or could be another object). The keys and values are separated by a colon :, and the key-value pairs are separated by commas ,.

You can access the properties of an object using dot notation (variable.key) or square bracket notation (variable['key']). For example:

`js
console.log(person.name); // Output: 'Rizwan Ashiq'
console.log(person["age"]); // Output: 30
console.log(person.education[1]); // Output: "MS Computer Science"
console.log(person.dob.year); // Output: 1996
`

You can also add, modify, or delete properties of an object using the assignment operator (=) or the delete operator. For example:

`js
person.height = 180; // Adding a new property height with value 180
person.name = "Jane"; // Modifying an existing property name with value "Jane"
delete person.isMarried; // Deleting a property isMarried
`

Objects are a powerful and flexible data type in JavaScript, and they are used to store and manipulate data in many contexts. You will learn more about objects in the next chapters.

Array

Data type of array is object. An array is used to store a list of values. An array can store any type of data, including numbers, strings, booleans, objects, and even other arrays.

Here is an example of how you can create an array in JavaScript:

`js
const numbers = [1, 2, 3, 4, 5];
const words = ["one", "two", "three"];
const mixed = [1, "two", true, null, { name: "Rizwan" }, [1, 2, 3]];
`

In this example, numbers is an array of numbers, words is an array of strings, and mixed is an array of mixed data types.

You can access the elements of an array using their index, which is the position of the element in the array. Array indices are zero-based, which means that the first element of an array has an index of 0, the second element has an index of 1, and so on.

You can access an element of an array using square brackets and the index of the element. For example:

`js
const numbers = [1, 2, 3, 4, 5];
const words = ["one", "two", "three"];

console.log(numbers[0]); // Output: 1
console.log(words[1]); // Output: 'two'
`

You can also use the length property of an array to find out how many elements it has. For example:

`js
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.length); // Output: 5
`

Complete example:

`js
const numbers = [1, 2, 3, 4, 5];

// Accessing an element of the array using its index
console.log(numbers[0]); // Output: 1

// Modifying an element of the array using its index
numbers[0] = 10;
console.log(numbers[0]); // Output: 10

// Adding a new element to the array
numbers[5] = 6;
console.log(numbers); // Output: [10, 2, 3, 4, 5, 6]

// Finding the length of the array
console.log(numbers.length); // Output: 6
`

Arrays are a powerful and versatile data type in JavaScript, and they are used to store and manipulate data in many contexts. You will learn more about arrays in the next chapters.

Symbol

Represents a unique and immutable identifier. Symbols are used to create unique object keys, and they are often used to ensure that object properties and methods do not conflict with each other.

Here is an example of how you can create a Symbol in JavaScript:

`js
const symbol1 = Symbol();
const symbol2 = Symbol("some description");
`

In this example, symbol1 is a Symbol with no description, and symbol2 is a Symbol with the description 'some description'.

You can use Symbols as object keys to create unique properties that can't be accessed or modified using the usual dot notation or square bracket notation.

`js
const person = {};

person[Symbol("name")] = "Ali";
person[Symbol("age")] = 30;

console.log(person[Symbol("name")]); // Output: 'Ali'
console.log(person.name); // Output: undefined
`

Symbols are a relatively new data type in JavaScript, and they are not used as often as other data types like numbers, strings, and booleans. However, they can be very useful in certain situations, particularly when you need to create unique and immutable identifiers.

Function

Function is a data type that represents a block of code that can be executed. Functions are used to perform a specific task, and they are often used to perform the same task multiple times.

Here is an example of how you can create a function in JavaScript:

`js
function add(a, b) {
return a + b;
}
`

In this example, add is a function that takes two parameters, a and b, and returns the sum of a and b.

You can call a function by using the function name followed by parentheses. For example:

`js
add(1, 2); // Output: 3
`

You can also assign a function to a variable. For example:

`js
const add = function (a, b) {
return a + b;
};
`

In this example, add is a variable that stores a function. You can call the function by using the variable name followed by parentheses. For example:

`js
add(1, 2); // Output: 3
`

Functions are a powerful and versatile data type in JavaScript, and they are used to perform a specific task in many contexts. You will learn more about functions in the next chapters.

typeof operator

The typeof operator is used to find the data type of value. It returns a string that represents the data type of the value.

Here is an example of how you can use the typeof operator:

`js
console.log(typeof 1); // Output: 'number'
console.log(typeof "one"); // Output: 'string'
console.log(typeof true); // Output: 'boolean'
console.log(typeof null); // Output: 'object'
console.log(typeof undefined); // Output: 'undefined'
console.log(typeof Symbol()); // Output: 'symbol'
console.log(typeof function () {}); // Output: 'function'
`

In this example, the typeof operator is used to find the data type of different values.

typeof null returns object instead of null
The typeof operator returns 'object' for null because null is an object. It is a bug in JavaScript that has not been fixed yet. So, you should not use typeof operator to check if a value is null or not.

`js
console.log(typeof null); // Output: 'object'
console.log(null === null); // Output: true
`

The typeof operator returns 'function' for functions because functions are objects in JavaScript. It is a bug in JavaScript that has not been fixed yet. So, you should not use typeof operator to check if a value is a function or not.

`js
console.log(typeof function () {}); // Output: 'function'
console.log(typeof {}); // Output: 'object'
`

Top comments (0)