DEV Community

Discussion on: For Loop in different programming languages

Collapse
 
ssalka profile image
Steven Salka

Nice post! When working with JavaScript/TypeScript, I usually go for the forEach array method, which is pretty convenient for usage with functions:

const fruit = ['apple', 'banana', 'orange'];

fruit.forEach(console.log);
// apple
// banana
// orange

If using a library like lodash, you can also iterate over objects (though iteration order is not guaranteed):

const funcs = {
  square: x => x ** 2,
  abs: x => Math.abs(x),
  reciprocal: x => 1 / x
};

_.forEach(funcs, (fn, fnName) => {
  console.log(`${fnName}(-2) = ${fn(-2)}`);
});
// square(-2) = 4
// abs(-2) = 2
// reciprocal(-2) = -0.5