instanceof
and typeof
are two operators to check the type of a value.typeof
operator checks if a value has type of primitive type which can be one of boolean
, function
, object
,
number
, string
, undefined
and symbol
(ES6).typeof 'helloworld'; // 'string'
typeof (new String('helloworld')); // 'object'
instanceof
operator checks if a value is an instance of a class or constructor function. 'helloworld' instanceof String; // false
new String('helloworld') instanceof String; // true
String
object, then you need to use both operators:const isString = value => typeof value === 'string' || value instanceof String;
isString('helloworld'); // true
isString(new String('helloworld')); // true
toString()
of Object
as below:const isString = value => Object.prototype.toString.call(value) === '[object String]';
isString('hello world'); // true
isString(new String('hello world')); // true
isString(10); // false
const isBoolean = value => Object.prototype.toString.call(value) === '[object Boolean]';
String
constructor:let message = new String('hello');
message instanceof String; // true
typeof message; // 'object'
message += ' world';
message instanceof String; // false
typeof message; // 'string'
typeof
with null
:typeof null; // 'object', not 'null'
instanceof
doesn't work for primitive types.instanceof
all the time, then you can override the behavior of instanceof
by implementing
a static method with the key of Symbol.hasInstance
.PrimitiveNumber
that checks if a value is a number:class PrimitiveNumber {
static [Symbol.hasInstance](value) {
return typeof value === 'number';
}
}
12345 instanceof PrimitiveNumber; // true
'helloworld' instanceof PrimitiveNumber; // false