Array-like objects in JavaScript
Table of Contents
In JavaScript, we have 3 types of array-like objects
1. Arguments
Arguments
is an array-like object that contains the values of the arguments passed to a function.
function sum() {
console.log(arguments)
}
sum(1, 2, 3)
// Output: Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
so, you can see index
and length
property in arguments
object.
2. DOM NodeList
NodeList
is an array-like object that contains all the nodes returned by document.querySelectorAll()
or document.getElementsByTagName()
.
const list = document.querySelectorAll('ul')
console.log(list)
// Output: NodeList(6) [ul, ul, ul,ul, ul, ul]
3. Strings
Strings
are array-like objects that contain a sequence of characters.
const str = 'Hello'
console.log(str)
// Output: Hello
Wait, something went wrong here, string is object ?
yes in javascript, behide the scene, 'Hello'
will be converted to new String('Hello')
.
and now you see a magic
How to convert array-like objects to arrays?
1. Using Array.from()
const list = document.querySelectorAll('ul')
const arr = Array.from(list)
console.log(arr)
// Output: [ul, ul, ul, ul, ul, ul]
const str = 'Hello'
const arr = Array.from(str)
console.log(arr)
// Output: ["H", "e", "l", "l", "o"]
2. Using spread operator
const list = document.querySelectorAll('ul')
const arr = [...list]
console.log(arr)
// Output: [ul, ul, ul, ul, ul, ul]
const str = 'Hello'
const arr = [...str]
console.log(arr)
// Output: ["H", "e", "l", "l", "o"]
3. Using Array.prototype.slice.call()
const list = document.querySelectorAll('ul')
const arr = Array.prototype.slice.call(list)
console.log(arr)
// Output: [ul, ul, ul, ul, ul, ul]
const str = 'Hello'
const arr = Array.prototype.slice.call(str)
console.log(arr)
// Output: ["H", "e", "l", "l", "o"]
Now, you can gossip with your friends about array-like objects in JavaScript. And don't forget to share this article with them. See you in the next article. Bye bye 👋