Hey programmer, in this article, we are going to learn how we can find the largest element in an array in JavaScript without using any function.
The largest element in an array refers to the value that holds the greatest numerical order among all elements available in the array. So below is the example of array input and the output what we will get also explains the value.
Example
Now let's jump to the code and see how we can Find Largest Number in Array in JavaScript.
Solution
What did we in this loop?
Array Initialization: Firstly we have initialized the array named array is defined with the values [3, 5, 6, 8, 2, 0].
Function Declaration: Then the function finaLargest is defined, which takes one parameter arr (which is the array).
Max Variable Initialization: Inside the function, a variable max is initialized with the first element of the input array arr (i.e., arr[0]).
Loop Through the Array: A for loop starts from the second element of the array (index 1) and continues until the last element.
Comparison Logic: Inside the loop, there is an if statement that checks if the current element (arr[i]) is greater than the current value of max.
If true, max is updated to the current element.
Logging the Result: After the loop, the largest number found is printed to the console with the message 'largest number: '.
Function Invocation: The function finaLargest is called with an array as an argument, which triggers the process of finding and printing the largest number.