In: Computer Science
How do we return the datatype of arguments without using type of in javascript
The alternative way of typeof operator is
Object.prototype.toString.
This
is a method that prints out the name of the
class that you passed into toString
.
JavaScript has seven primitive data types and Object:
boolean, null, undefined, number, BigInt, string, symbol and
object.
You can use below code to check the data type of each
arguments.
Javascript code:-
function checkType(val){
return Object.prototype.toString.call(val).slice(8,-1);
}
console.log(checkType('Test'));
console.log(checkType(1));
console.log(checkType(undefined));
console.log(checkType(true));
console.log(checkType([1,2,3]));
console.log(checkType({}));
console.log(checkType(null));
output:-
Code Summary:
In above code we created function checkType() that returns a data type of a given arguments and we are printing the output of that using console.log() method.
Note Object.prototype.toString.call() return a result in format [Object object], e.g. [Object Number]. So just to have a Number as output we are slicing the result using slice method.
Output in console:-