Course contentsShow
← JavaScript
Lesson 840 of 2,72319. ArraysFree lesson

Array.from with Array-Like Objects

Convert array-like objects such as NodeLists and arguments into real arrays using Array.from.

Array.from with Array-Like Objects

You'll learn how to convert array-like objects (such as NodeLists and arguments) into true arrays using Array.from.

JavaScript has several objects that look like arrays but aren't real arrays. They have numbered properties and a length property, but they lack array methods like push(), map(), or filter(). Common examples include:

  • NodeLists returned by document.querySelectorAll()
  • The arguments object inside functions
  • Strings (which are iterable and have indexed characters)

These are called "array-like objects." To use array methods on them, you need to convert them first.

Converting Array-Like Objects

Array.from() takes an array-like (or iterable) object and returns a real array:

function showArgs() {
  console.log(typeof arguments);        // "object"
  console.log(Array.isArray(arguments)); // false
  
  const realArray = Array.from(arguments);
  console.log(Array.isArray(realArray)); // true
  realArray.push('extra'); // Now we can use array methods!
  return realArray;
}

showArgs('a', 'b', 'c'); // ['a', 'b', 'c', 'extra']

Why This Matters

Before Array.from(), converting array-likes required awkward workarounds. Now you can easily transform NodeLists, arguments, or any iterable into a working array, unlocking all the array methods you've learned.

Think of it like converting foreign currency: array-like objects have value (the data), but you need to exchange them into the right format (a real array) before you can spend them at certain stores (use array methods).

Key Takeaway: Array.from() converts array-like objects and iterables into real arrays, giving you access to all array methods.