Arrays

Consider an example
const myArray = [1,'hi',true,{name:'socks'},[1,2]]
console.log(type of([1,2])) //object
console.log(myArray.isArray[1,2])//true
const myArray = [1,'hi',true,{name:'socks'},[1,2]]
console.log(type of([1,2])) //object
console.log(myArray.isArray[1,2])//true
What is the difference here in typeof and isArray can anyone pls help.
7 Replies
glutonium
glutonium2mo ago
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
Jochem
Jochem2mo ago
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:
const myArray = [1,'hi',true,{name:'socks'},[1,2]];
console.log(typeof [1,2]) //object
console.log(Array.isArray([1,2]))//true
const myArray = [1,'hi',true,{name:'socks'},[1,2]];
console.log(typeof [1,2]) //object
console.log(Array.isArray([1,2]))//true
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.
glutonium
glutonium2mo ago
btw, another similar property is NaN (Not a number) typeof NaN returns number so u have to use isNaN()
Vandana
Vandana2mo ago
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 ??
glutonium
glutonium2mo ago
well u see, if u have 2 variables
let x = NaN;
let y = 69;
let x = NaN;
let y = 69;
and u wanna know which one contains an actual number, if you use typeof
typeof x // -> Number
typeof y // -> Number
typeof x // -> Number
typeof y // -> Number
but if you use isNaN,
isNaN(x) // -> true
isNaN(y) // -> false
isNaN(x) // -> true
isNaN(y) // -> false
Vandana
Vandana2mo ago
Well explained by a very good example I do really appreciate it .Thanks
glutonium
glutonium2mo ago
welcm
Want results from more Discord servers?
Add your server