Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active March 22, 2024 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/aee45b54e69e094b968481f1e341ae26 to your computer and use it in GitHub Desktop.
Save dfkaye/aee45b54e69e094b968481f1e341ae26 to your computer and use it in GitHub Desktop.
What's "in" an array?
// 29 September 2023
// What's in an array?
// Here's an array:
var a = [1,2,3,4];
// If we use want only the *own* properties of an array, we can use the
// Object.keys() method to inspect it.
Object.keys(a).forEach(n => {
console.log(n, typeof n);
});
/*
0 string
1 string
2 string
3 string
*/
// Wait, why is 'length' not included if every array has a 'length'?
// Object.keys() finds only those keys that are "enumerable".
// To find *own* keys that are not enumerable, we use
// Object.getOwnPropertyNames().
// That turns up the 'length' field in the result.
Object.getOwnPropertyNames(a).forEach(n => {
console.log(n, typeof n);
});
/*
0 string
1 string
2 string
3 string
length string
*/
// The 'in' keyword is not the array.includes() method, it returns true if a
// value is a key in an object.
console.log(`'length' in a:`, 'length' in a);
/*
'length' in a: true
*/
// The 'for-in' loop searches enumerable keys in the object as well as its
// prototype chain.
// The 'for-in' loop on an *array*, however, returns the same result as the
// Object.keys() method.
for (var n in a) {
console.log(n, typeof n);
}
/*
0 string
1 string
2 string
3 string
*/
// Again, the 'length' field does not appear in the for-in loop result because
// it not "enumerable".
// Did you notice that neither are these methods?
console.log(`'push' in a:`, 'push' in a);
console.log(`'toString' in a:`, 'toString' in a);
console.log(`'valueOf' in a:`, 'valueOf' in a);
/*
'push' in a: true
'toString' in a: true
'valueOf' in a: true
*/
// These are not *own* properties either, else they would appear in the
// Object.keys() and Object.getOwnPropertyNames() results, but are inherited
// from the Array prototype.
Object.keys(Array.prototype).forEach(n => {
console.log(n);
});
// No result printed!
// That's because they are not "enumerable", and we need to find them using the
// Object.getOwnPropertyNames() method instead.
Object.getOwnPropertyNames(Array.prototype).forEach(n => {
console.log(n);
});
/*
length
toString
toLocaleString
join
reverse
sort
push
pop
shift
unshift
splice
concat
slice
lastIndexOf
indexOf
forEach
map
filter
reduce
reduceRight
some
every
find
findIndex
copyWithin
fill
entries
keys
values
includes
flatMap
flat
at
findLast
findLastIndex
toReversed
toSorted
toSpliced
with
constructor
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment