You can use instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. Thus, it’s safe to say that instanceof is applicable only for objects rather than primitive types. For instanceof String, you can use the typeof method in JavaScript.
Use typeof "foo" === "string"
instead of instanceof.
On the other hand, the typeof operator tests whether the value belongs to primitive types like “string”, “number”, “boolean”, “object”, “function”, or “undefined”.
Check JavaScript instanceof String
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
var a = "Hello World";
var b = new String("Hello World");
console.log(a instanceof String); //false;
console.log(b instanceof String); //true;
if (typeof a === "string"){
console.log(a)
}
</script>
</body>
</html>
Output:
Note: the instanceof
operator with primitive values like strings, numbers, and booleans is generally not necessary in everyday programming. It’s more commonly used with custom classes or constructor functions when dealing with object-oriented programming in JavaScript.
Do comment if you have any doubts or suggestions on this JS string topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version