

A callback function is a simple function that defines the operation to be performed on a single element, and the forEach() method makes sure it will be performed on each element of an array. You can customize the performed operations using a callback function - a function passed as a parameter of the forEach() method. You can use it to loop through an array and perform a certain operation on each of its elements - though, map() is more commonly used for this purpose. The forEach() is a method of the Array class. In this article, we'll see how to get the current element's array index in JavaScript using the forEach() method. This is very straightforward to achieve using the index parameter of the forEach() method.

In fact, you can't even extract the value of an element if you don't know its place in the original array.ĭuring iteration, the index of the current element may be relevant to you.

The fact every array is ordered means that the place of each element is of great importance. It is essentially a class that encapsulates an array (an ordered list of values) and all necessary methods you might need to perform array operations. In simple terms, you can look at the Array object as an array in any other programming language. length, it returned twice the expected value! Switching to the spread operator fixed the problem.An Array in JavaScript is a standardized, built-in object used to store multiple objects under the same name. call ( 'word', eachLetter => eachLetter ) // ['w', 'o', 'r', : ('string') wil do the trick Extra info: it's safer to use the spread operator (second method) rather than ('') (first method), because split() doesn't work with some uncommon I had a string that contained special characters like åæāă etc. Since this is just an article, I'll paste the result here so you can follow along.Īrray. Feel free to copy the code and paste in the playground, where you can hover on the variable to view the types. This is more evident if we use the TypeScript Playground. # TypeScript Test: Result array is not a string type 😱 Which means we have an Array PLUS some string methods. So what we're doing here Object.assign(, string) it copying ALL of our string properties over to our new array. The key there is "copies all enumerable own properties". The Object.assign() method copies all enumerable own properties from one or more source objects to a target object

One thing to note Object.assign is that it doesn't actually produce a pure array. The newer methods spread and om are better equipped to handle these and will split your string by grapheme clusters 👍 # A caveat about Object.assign ⚠️ This is what's called grapheme clusters - where the user perceives it as 1 single unit, but under the hood, it's in fact made up of multiple units.
