Arrays in JavaScript are special objects, so methods [Object.keys], [Object.values], [Object.entries] work with them too:
const arr = ['a', 'b', 'c'];
Object.keys(arr); // ['0', '1', '2'] — indices
Object.values(arr); // ['a', 'b', 'c'] — values
Object.entries(arr); // [['0','a'], ['1','b'], ['2','c']] — pairsArrays in JavaScript are like special objects with numbered “pockets”. [Object.*] methods work with them as with regular objects! 📦🔢
Returns all “pocket names” (indices) as strings:
const fruits = ['apple', 'banana', 'orange'];
console.log(Object.keys(fruits));
// ['0', '1', '2'] — indices as strings!
// Missing elements are not counted
const sparse = ['a', , 'c']; // "sparse" array
console.log(Object.keys(sparse));
// ['0', '2'] — only existing indicesReturns values of all elements:
const fruits = ['apple', 'banana', 'orange'];
console.log(Object.values(fruits));
// ['apple', 'banana', 'orange'] — like arr.slice()
// Missing elements also not counted
const sparse = ['a', , 'c'];
console.log(Object.values(sparse));
// ['a', 'c'] — only existing valuesReturns array of [index, value] pairs:
const fruits = ['apple', 'banana', 'orange'];
console.log(Object.entries(fruits));
// [['0', 'apple'], ['1', 'banana'], ['2', 'orange']]
// Useful for iteration with indices
Object.entries(fruits).forEach(([index, value]) => {
console.log(`${index}: ${value}`);
});
// 0: apple
// 1: banana
// 2: orange// ✅ When you need indices as array
const arr = ['a', 'b', 'c'];
const indices = Object.keys(arr); // ['0', '1', '2']
// Better than making loop to get indices// ✅ Keep only even indices
const arr = ['a', 'b', 'c', 'd'];
const evenIndexed = Object.entries(arr)
.filter(([index]) => index % 2 === 0)
.map(([, value]) => value);
console.log(evenIndexed); // ['a', 'c']const arr = ['a', 'b', 'c'];
const keys = Object.keys(arr);
// ❌ Mistake — these are strings!
console.log(keys[0] + 1); // '01', not 1!
// ✅ Correct — convert to number
console.log(+keys[0] + 1); // 1const arr = ['a', 'b', 'c'];
// ❌ Not the same!
Object.values(arr); // ['a', 'b', 'c']
arr.slice(); // ['a', 'b', 'c'] — same, but clearer
// Object.values is more useful with objectsUnderstanding how Object.* methods work with arrays helps better understand how arrays are structured in JavaScript! 💡
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪