Could someone please explain the following?
[] instanceof Array; // true
'' instanceof String; // false
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.
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.
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).
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.
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"
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With