You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Purpose: basic alternative to the for loop that bypasses use of array indexes
Use when: you need to do an operation with side-effects (like writing to a file, outputting something on screen, adding content directly to the DOM)
Returns: undefined
Syntax:
myArray.forEach((element,index,array)=>{// code with effects goes here// Note: index and array parameters are optional});
Example:
constfs=require('fs')constfilenames=['temp1.txt','temp2.txt','temp3.txt']// delete files in the arrayfilenames.forEach(filename=>{fs.rm(filename,err=>console.log(err ? `Failed to delete ${filename}` : `Successfully deleted ${filename}`));})
.map()
Purpose: to transform an array of values into a new array of values
Use when: you have a list of things that you need to transform item by item into another list
Returns: a new array of values output by the callback function
Syntax:
myArray.map((element,index,array)=>{// code that returns a value goes here// Note: index and array parameters are optional});
Purpose: to filter values in an array based on some criteria
Use when: you have some criteria for filtering or continuing processing that you want to apply
Returns: a new array of values from the original array where the callback returned a truthy value
Syntax:
myArray.filter((element,index,array)=>{// code that returns true or false (actually truthy or falsy) goes here// Note: index and array parameters are optional});
Purpose: to convert an array of values to a single value (even an object)
Use when: you want to convert an array to a single value or object
Returns: a single value
Syntax:
myArray.reduce((previousAccumulatedValue,currentValue,currentIndex,array)=>{/* code that returns new accumulated value */},initialValue// Note: currentIndex and array parameters are optional});
this is a BIG help! thank you Brian :)