
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Return Highest Value from an Array in JavaScript
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
Advertisements