I want to explain the differences between the typeof
and instanceof
operators in object-oriented JavaScript. Both of these operators can be used to find out more information about a certain piece of data.
typeof
is an operator that can be used to verify what datatype a certain "operand" is. An "operand," as mentioned in the MDN documentation, is just a piece of data that is being manipulated or worked on. This operand can be pretty much anything, from a variable that contains a value to a function. When using typeof
on an operand, all you need to is simply state typeof
right before the operand.
Here are two examples:
const a = 6;
typeof a;
//"number"
function hello(name) {
return `hello, ${name}`
}
typeof hello
//"function"
typeof hello()
//"string"
In the first example, we are using typeof
on the variable a
, which contains the value of integer 6. Therefore, the return value is "number," because 6 is a number/integer.
The second example is a little more tricky. Here, we have the hello
function. When using typeof
on hello
, we get the return value of function.
This is because hello
refers to the function body, or the code that is between the brackets, also known as the code block. If we call typeof
on hello()
, however, we get the value of string
. This is because the function is now being invoked, and therefore returns the string within the code block.
The instanceof
operator tests to see whether the operand is an instance, or object, of a certain class. In JavaScript, just like initialize
method in Ruby, instances of a class can be created/initialized with certain attributes using the constructor
method. This makes each instance of a class unique. Let's take a look at this example:
class Person {
constructor(name,age) {
this.name = name
this.age = age
}
}
const person = new Person('David',22)
const david = new Person
console.log(person.name)
//"David"
console.log(person.age)
//22
In this Person
class, each new instance of Person
will be created with a name and an age. this
refers to the object/instance that is currently being created and initialized. this
is similar in concept to self
in Ruby.
With this knowledge of the constructor method in JavaScript, we can use the instanceof
operator to verify whether the operand is actually an instance of a certain class. typeof
returns a boolean value. Using the Person
class above, we can use instanceof
to verify whether person
is an instance of the Person
class.
console.log(person instanceof Person;)
//true
console.log(david instanceof Person;)
//true
When applying this to person
and david
, we can see that both of the expressions return the value of "true." This is because both are instances of the Person
class.
To summarize, typeof
and instanceof
are neat little operators that can be utilized when trying to verify the properties/characteristics of objects and data in JavaScript.
Top comments (0)