One Line For Loop
What is not often realized is that for loops are more of a pattern that a language construct. Specifically:
for (<initialize>;<check>;<assign>)
The initialization can be for anything, but it is usually for variables scoped to the block of the function. Check is any set of conditions that cause the for loop to continue. And assign is just a place where anything can be assigned after the check has passed. Technically, only the check part is necessary (remember that you can assign and initialized in the for body). By leaving the initialize out and putting it in a function body, very simple code can be written:
var contains = function(arr, value) { var i = 0; for (; i < arr.length && arr[i] !== value; i += 1); return i < arr.length; }; var arr = [1,2,3,4]; console.log(contains(arr, 3));// true
It even stops early due to the second condition. The last part is usually used with an increment. But that is just a special case, any type of assign can be done. Additionally, multiple assigns can be given with a comma operator. Which allows something like this:
var findMax = function(arr, value) { var i = 0, max = Number.MIN_VALUE; for (; i < arr.length; max = max < arr[i] ? arr[i] : max, i += 1); return max; }; console.log(findMax([5,1,8,2]));// 8
For readability purposes, it is probably best not to go beyond the above level of complexity though.
Finally, in most cases using list abstractions from libraries like Lodash removes the need for most for loop operations. But there are a few cases when for loops still should be used. Like when a part of code needs to be heavily optimized (e.g. animation); using for loops in place of a bunch of function calls is much faster as function calls are expensive in JavaScript relatively. So it is still useful to fully understand the nature of for loops.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2016/oneLineForLoop.js














