DEV Community

Discussion on: When is an array, not an array?

Collapse
 
antogarand profile image
Antony Garand • Edited

This weird behavior is caused by arrays, which are actually JavaScript objects!

console.log(typeof [1,2,3]);  
// object  

As they are objects, they can still have properties and other content injected via the bracket notation.

We can confirm this by checking the keys vs the array length:

const x = [1,2,3];  
console.log(x.length);  
// 3  
x[-1] = -1;  
console.log(Object.keys(x));  
// Array(4) [ "0", "1", "2", "-1" ]  
console.log(x.length);  
// 3  

When adding a value at a super high index, it behaves somewhat like a normal array:

const x = [1,2,3];  
x[100000] = `high`;
console.log(x.length);
// 100001
console.log(x);
// Array(100001) [ 0...9999] [10000...19999] ...

Love your podcast btw!

Collapse
 
thejoezack profile image
Joe Zack

Hey thanks!

Also, did you know that you can set the length property?

Check this out:

var x = [1,2,3,4,5];
x.length = 2;
// end up with [1,2]
Collapse
 
antogarand profile image
Antony Garand

Yea, that's a nice way to trim the end of an array!

Interesting but weird behavior, it suits JS