There are 4 ways to defind data types of JavaScript: 1. typeof, 2. instance of, 3. Object.prototype.toString.call(), 4. constructor. hope this helps.
JavaScript data types
JavaScript has 8 built-in types, expecting object, they are all called “basic type”. Which are:
null undefined boolean number string object symbol bigInt
1. typeof
typeof is not a function but a operator, it returns a string indicating the type of the unevaluated operand, includes number, boolean, symbol, string, object, undefined, function and bigInt.
javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14
console.log(typeofundefined) // undefind console.log(typeofnull) // object console.log(typeoftrue) // boolean console.log(typeof43) // number console.log(typeof'21') // string console.log(typeof {a:1}) // object console.log(typeofSymbol()) // symbol console.log(typeof123n) // bigint functiona() {} console.log(typeof a) // function var date = newDate() var error = newError() console.log(typeof date) // object console.log(typeof error) // object
2. instanceof
instanceof operator is used to see if prototype property A a constructor is appears anywhere in the prototype chain of B, the return value is a boolean value.
toString() is an origin method of Object, to use, it simply return its [[Class]]. This is an internal attribute, its syntax is [object Xxx], Xxx is the type of object. For anyother objects, inorder to get the right type, needs to use call/apply method.
The examples from the previous chapters are limited. They only create single objects. Sometimes we need a “blueprint” for creating many objects of the same “type”. The way to create an “object type”, is to use an object constructor function.