Type checking in JavaScript ( typeof and instanceof)
JavaScript is an inexactly composed language, so there is no limitation on the variable’s type.
For example, on the off chance that you’ve made a variable with a string type, later you can assign to a similar variable a number:
Such dynamism gives you flexibility and simplifies variables declaration.
On the opposite side, you can never be certain that a variable contains a worth of a particular type. For instance, the accompanying function say(msg) anticipates a string contention, nonetheless, you can summon the function with a argument:
That is the reason, now and again, you need to check the variable’s type in JavaScript — utilizing typeof
operator, just as instanceof
to check instance types.
Let’s see in more detail how to use typeof
and instanceof
operators in JavaScript.
1. typeof operator
In JavaScript, you can discover primitive types like strings, numbers, booleans. Also, there are function, objects, and the unique special value undefined and null.
typeof is the operator that we should you decide the type of the expression:
const typeAsString = typeof expression;
where expression assesses to a worth which type you’d prefer to discover. expression can be a variable myVariable,
Let’s see how typeof
operator works for various type:
I.Strings
II.Number
III.Booleans:
IV.Symbols:
V.undefined:
VI.Objects:
VII.Functions:
2. instanceof operator
The typical method to utilize a JavaScript function is to invoke it’s anything but a couple of parentheses after its name:
say('Hello World');
is a regular function invocation.
Be that as it may, JavaScript function can accomplish more: they can even construct objects! To make a function construct objects, simply utilize new keyword before the regular function invocation:
new say('Hello World')
is a constructor invocation that makes the instance longmsg .
How might you check in JavaScript that a specific instance was made with a specific constructor? :
where object is an expression that assesses to an object, Contructor is a class or function that develops objects. instanceof assesses to a boolean.
longmsg
instance was made utilizing say
constructor, so longmsg
instanceof say
assesses to true.
You can construct object by using class
, For eg. et's define a class language
and then created an instance of it myStack
:
Here new Language('Javascript')
is constructor invocation which create an instance myStack
.
Now myStack instanceOf Language
also evaluates to true
.
myStack instanceof Language;
3. Summary
JavaScript is an approximately composed language, implying that there is no restrictions on what type a variable can have.
typeof expression
is the operator that allows you to decide the type of expression. typeof
assesses to one of the values: string
, number
, boolean
, symbol
, undefined
, object
, function
.
Share your valuable feedback so that I can improve my article further.
Thank you for reading
Originally published at https://shantun.tech.