We are required to write a JavaScript function that takes in an array of Numbers. Our function should iterate through the array and pick the greatest (largest) element from the array and return that element.
Example
The code for this will be −
const arr = [5, 3, 20, 15, 7]; const findGreatest = (arr = []) => { let greatest = -Infinity; if(!arr?.length){ return null; }; for(let i = 0; i < arr.length; i++){ const el = arr[i]; if(el < greatest){ continue; }; greatest = el; }; return greatest; }; console.log(findGreatest(arr));
Output
And the output in the console will be −
20