HOME

JavaScript

Loops/Iterators
  • .filter()
    • When need to filter an array
  • .map()
    • When need to transform an array
  • .reduce()
    • When need to reduce an array to a single value
  • .find()
    • When need to find an item in an array
  • .forEach()
    • When need to iterate over an array.
    • Doesn't work over iterables objects like Set or Map.
    • Executes a provided function once for each array element
    • Always returns undefined
    • Does not mutate the original array, but the callback may
    • Does not skip empty elements
    • Does not return a new array
    • Does not execute the function for array elements without values
    • There is no way to stop or break a .forEach() loop other than by throwing an exception
    • If plan to use async/await inside .forEach() loop, use for...of instead. This is because forEach() will not wait for your async function to complete before moving on to the next item, which can cause unexpected behavior.
  • .for...of
    • When need to iterate over an array
    • More general looping construct than .forEach(). Introduced in ES6.
    • Works with any iterable object, not just arrays.
    • Can use break, continue and return statements.
    • Don't have access to the index of each element, unless you create a counter variable.
  • .for...in
    • When need to iterate over the properties of an object

setInterval
useEffect(() => {
  const interval = setInterval(() => {
    // code
  }, 1000);
  return () => clearInterval(interval);
})