
Each method has different features, and it is up to you, depending on what youre doing, to decide which one to use. In this loop, the variable i automatically receives the index so that each character can be accessed using str.Įxample: // for. The JavaScript forEach method is one of the several ways to loop through arrays. This is different from the ordinary for loop that we studied before. There exists a special form of the loop: for.in. To walk over all the characters of a string, we can use an ordinary for loop, with a loop counter ( i) to go through string index from 0 to str.length: // ordinary for loop let str = "Buzz" Use the string index number to loop through a string for loop

There is no need to add brackets after it. Please note that str.length is a numeric property, not a function. The length property has the string length, it simply returns the number of characters in the string: let str = "hello123" Īlert(str.length) // 8 // the last character The following codes are for comparison between for loop and forEach() using an array of 20 consisting of millions items simple value addition and assignment where the execution times are printed.Looping Through a String The length Property

Is that really true? To prove that using a for loop is more efficient than forEach(), I did the following experiment.Įxperiment: Comparison with Simple Value Addition and Assignment In order to be able to directly modify array elements within the loop precede. It can be used to access and print out each property’s value, as demonstrated by the example code provided. The ‘for in’ loop is a useful tool for iterating over the enumerable properties of an object in JavaScript.


Removing optimizations that we had done on purpose The foreach construct provides an easy way to iterate over arrays. If you need to iterate over an ordered list, you should use a ‘for’ loop or a ‘for of’ loop with an array. I believe the above refactored codes also intend to achieve a better readability and maintainability, but the member of rxjs library rejects the changes and claim that it is Those utility functions greatly improve our productivity in array operations by using functional programming paradigm and they are clearer to read and easier to understand. So basically, the author would like to refactor the for loop by using forEach() in array utility functions.Īs we know, JavaScript / TypeScript has a set of powerful array utility functions including forEach(), map(), reduce() and so on. Enter fullscreen mode Exit fullscreen mode
