What is an ‘array-like object’ in JavaScript?
An object that has indexed access (elements can be accessed using numerical indexes like myObj[0]) and a length property, but lacks most built-in array methods (like push, pop, map, filter). It’s not a true array.
Give two common examples of array-like objects in JavaScript.
Why are array-like objects less convenient than true arrays?
They don’t have built-in array methods (like push, pop, map, filter, etc.).
How can you convert an array-like object into a real JavaScript array? Give two methods.
Explain how to use Array.from() to convert the arguments object to a real array and double each value.
function myFunction() {
const argsArray = Array.from(arguments, (arg) => arg * 2);
return argsArray;
}
console.log(myFunction(1, 2, 3)); // Output: [2, 4, 6]
Explain how to use the spread syntax to convert a NodeList to a real array.
const nodeList = document.querySelectorAll(‘li’);
const nodeArray = […nodeList];
What are the benefits of converting an array-like object to a real array?
• You can use all built-in array methods.
• The code becomes more readable.
• It’s a modern JS best practice.
What is a potential downside to converting an array-like object?
Performance: Converting a very large array-like object into an array might have a slight performance cost.
True or false: Array-like objects inherit from Array.prototype.
False. They lack standard array methods because they don’t inherit from Array.prototype.
What happens if you try to use an array method directly on an array-like object (e.g., arguments.push(4))?
You’ll get a TypeError, because array-like objects don’t have Array methods until converted.