Computer >> Computer tutorials >  >> Programming >> Javascript

Is it possible to create a new data type in JavaScript?


Yes, you can use the concept of Class. If you want to check the actual data type then you can use instanceof.

The instanceof tells about the data type. Here is the sample JavaScript code which will give a brief description about how to create a new data type and how to check the data type. Here, I will give the custom implementation to check the data type.

Example

Following is the code −

//creating the class
class Game {
   constructor(gameName) {
      this.gameName = gameName;
   }
}
//creating an object
const ticTacToe = new Game("TicTacToe");
// checking the data type.
function dataTypeBelongsTo(object) {
   if (object instanceof Game)
      return "Game";
   return typeof object; 
}
console.log("The ticTacToe is the object of Game class=" + (ticTacToe instanceof Game));
console.log("The data Type of ticTacToe is =" + dataTypeBelongsTo(ticTacToe));
console.log("The data Type Candy Cash is =" + dataTypeBelongsTo("Cady Cash"));

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo288.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo288.js
The ticTacToe is the object of Game class=true
The data Type of ticTacToe is =Game
The data Type Candy Cash is =string