Many times introduction to functional material tends to focus on really facile aspects of functional programming like "Use map
or reduce
instead of a for loop". To me this doesn't do justice to what a beginner functional approach really should be.
A good example to display how different the two approaches can be would be a simple range function
function range(start, end, step = 1) {
let numBetween = [];
const rangeStep = start < end ? Math.abs(step) : Math.abs(step) * -1;
const loopCond = (i) => (start > end ? end <= i : end >= i);
for (let i = start; loopCond(i); i += rangeStep) {
numBetween.push(i);
}
return numBetween;
}
const range = (start, end, step = 1) => {
const rangeLength = Math.ceil((Math.abs(start - end) + 1) / Math.abs(step));
const stepVal = start < end ? Math.abs(step) : Math.abs(step) * -1;
return [...new Array(rangeLength)].map(
(_, i) => i * stepVal + start
);
};
A decent amount can be said about either approach here but the big things I would implore the beginner to grasp is that in the imperative approach is much more of a step by step walk through of how you want the final array to be constructed value by value. The functional approach is more of a data transformation- you want an array of a certain length and the array values should follow a given pattern.