Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instanceof inconsistency

Tags:

javascript

Could someone please explain the following?

[] instanceof Array; // true
'' instanceof String; // false
like image 925
Randomblue Avatar asked Dec 20 '11 00:12

Randomblue


People also ask

What is inconsistency?

1 : the quality or state of not being in agreement or not being regular The team's biggest problem is inconsistency. 2 : something that is not in agreement or not regular There are inconsistencies in her story. Namesake of the leotard, Jules Léotard had what profession? Test your knowledge - and maybe learn something along the way.

What is the return type of instance of instanceof?

It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false. Let's see the simple example of instance operator where it tests the current class. An object of subclass type is also a type of parent class.

What is the use of instanceof in Java?

In Java, instanceof keyword is a binary operator. It is used to check whether an object is an instance of a particular class or not. The operator also checks whether an object is an instance of a class that implements an interface (will be discussed later in this tutorial).

How to check if an object is an instance of class?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. Here, if objectName is an instance of className, the operator returns true. Otherwise, it returns false. In the above example, we have created a variable name of the String type and an object obj of the Main class.


2 Answers

Note the following:

"" instanceof String;             // => false
new String("") instanceof String; // => true

instanceof requires an object, but "" is a string literal, and not a String object. Note the following types using the typeof function:

typeof ""             // => "string"
typeof new String("") // => "object"
typeof []             // => "object"
typeof new Array()    // => "object"
like image 70
Jon Newmuis Avatar answered Sep 29 '22 11:09

Jon Newmuis


It's because '' is primitive, not an object.

Some primitives in JavaScript can have an object wrapper. These are created when you make an instance of the wrapper using the built in constructor with new.

The new is typically necessary because often times the function will coerce to a primitive if you exclude new.

typeof new String('');  // "object"
typeof String('');      // "string"
typeof '';              // "string"

The primitives that have Object wrappers are string, number and boolean.

The primitives that do not are null and undefined.

like image 28
2 revsuser1106925 Avatar answered Sep 29 '22 09:09

2 revsuser1106925