JSFiddle - React, Tailwind, and code Playground

by joplomacedo

JavaScript

// RECURSIVE FUNCTION
// calls itself
// sometimes it's easier to do some looping logic with a recursive function
// many other times you can rely on a simple for loop
// this is a stupid example of a recursive function
function print1To( times, i = 0 ) {
	if ( i < times ) {
  	i++;
		console.log(i);
    print1To(times, i);
  }
}

print1To(5);
// prints:
// 1
// 2
// 3
// 4
// 5


// HIGHER ORDER FUNCTION
// 1) returns another function (like the memoization function) or
// 2) receives another function as an argument (like this one below)
function forEach( arr, func ) {
	for (let i = 0; i < arr.length; i++) {
  	func(arr[i], i);
  }
}


const fruits = ['apple','banana','pear'];

forEach(fruits, ( fruit, i) => {
	console.log('fruit: ' + fruit);
})

// prints:
// fruit: apple
// fruit: banana
// fruit: pear