The following example code demonstrates How to Find the Minimum and Maximum from an Array in JavaScript.
In order to find the maximum and minimum value from the array, first we need to create the array. So, the first line in the code creates the array arr. Also, it initializes the array with integer values. After that, we use the for loop to display the array elements. The variables min and max are assigned the first element of the array. Further, the loop iterates from the second element to the last element.
When an element encounters that is smaller than min, we set the min to that element. Similarly, we update the value of max when any element larger than max is found. So, when the loop terminates, the min and max variables hold the minimum and maximum values respectively.
<html>
<head>
<title>Minimum and Maximum</title>
<script>
arr=[12, 9, -20, 11, 100, 56, 20, -523, 68, 32];
document.write("Array Elements: <br>");
for(i=0;i<arr.length;i++)
document.write(arr[i]+" ");
min=arr[0];
max=arr[0];
for(i=1;i<arr.length;i++)
{
if(min>arr[i])
min=arr[i];
if(max<arr[i])
max=arr[i];
}
document.write("<br>Minimum = "+min);
document.write("<br>Maximum = "+max);
</script>
</head>
<body>
</body>
</html>
Output
Further Reading
Evolution of JavaScript from ES1 to ES2020
Introduction to HTML DOM Methods in JavaScript
Understanding Document Object Model (DOM) in JavaScript
Understanding HTTP Requests and Responses
What is Asynchronous JavaScript?
JavaScript Code for Event Handling
- AI
- Android
- Angular
- ASP.NET
- Augmented Reality
- AWS
- Bioinformatics
- Biometrics
- Blockchain
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Cyber Security
- Data Science
- Data Structures and Algorithms
- Data Visualization
- Datafication
- Deep Learning
- DevOps
- Digital Forensic
- Digital Trust
- Digital Twins
- Django
- Docker
- Dot Net Framework
- Drones
- Elasticsearch
- ES6
- Extended Reality
- Flutter and Dart
- Full Stack Development
- Git
- Go
- HTML
- Image Processing
- IoT
- IT
- Java
- JavaScript
- Kotlin
- Latex
- Machine Learning
- MEAN Stack
- MERN Stack
- Microservices
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Quantum Computing
- React
- Robotics
- Rust
- Scratch 3.0
- Shell Script
- Smart City
- Software
- Solidity
- SQL
- SQLite
- Tecgnology
- Tkinter
- TypeScript
- VB.NET
- Virtual Reality
- Web Designing
- WebAssembly
- XML