JavaScript: Type Operators

Profile picture for user arilio666

So in javascript, there is an operator to check the instance of a class and check the type of a value within a variable.

1. Typeof

So it is basically an operator to check the datatype of a value present inside a variable and respond to what type is present inside the variable.

Example - string:

var name = 'neo'
console.log(typeof name)

Output: string

Example - number: 

var num = 21
console.log(typeof num)

Output: number

Example - boolean: 

var name = true
console.log(typeof name)

Output: boolean 

Example - object: 

var ra = [12,2,2,1]
console.log(typeof ra)

Output: object

So you might get the idea right. It basically gets the data type of the value that the variable is holding.

2. Instanceof

It generally finds or verifies out whether the object created from a class is actually an instance of the respective class or not.

Example: When object is instance of class

class matrix {


ma = new matrix();
console.log(ma instanceof matrix)

Output: true

Here 'ma' is an instance of the class matrix because it was used to create an object from the matrix class.

Example: When object is not the instance of class

class matrix {


class zion {


ma = new matrix();
console.log(ma instanceof zion)

 Output: false

Here it represents the pessimistic scenario where we have given zion class name for ma object of class matrix and check whether ma is instance of zion or not, which will eventually return false.