Arrays
Consider an example
What is the difference here in typeof and isArray can anyone pls help.
7 Replies
well u see in js, Arrays are just objects in disguise. so the underlying structure is similar to of an object. so natively the typeof Array is an object
but because of that there's not really a way to know if a data is an array of not. cause typeof returns object for an array due to the reason mentioned before. so in order to have a way to know if a data is an array or not the Array.isArray() was introduced
so to summarise
- arrays in js are just objects in disguise
- hence typeof array returns object
- hence we don't really have a way to identify an array
- hence Array.isArray() was introduced
also, just looking at your code, there's a couple of issues.
typeof
is a keyword, not a function with a space in it. It doesn't take brackets.
isArray
is a static method of the Array
class, not a method of any array that you have. It is however a method that needs calling brackets like any other
The correct version of the code would be:
On line 1, you define an array that is then never used again.
Line 2 prints "object" because of what glutonium explained.
And Array.isArray()
returns true because you're feeding it a fresh array of two elements.btw, another similar property is NaN (Not a number)
typeof NaN returns number
so u have to use isNaN()
Thanks for the explaination guys.
But then we know typeof NaN is number ONLY.we are using isNaN() to check whether it is a number or not am i write ??
well u see,
if u have 2 variables
and u wanna know which one contains an actual number,
if you use typeof
but if you use isNaN,
Well explained by a very good example I do really appreciate it .Thanks
welcm