0

Good day everyone!

I've found this great code from this site:

var points = [30,100];
document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
    var len = arr.length;
    var max = -Infinity;
    while (len--) {
      if (arr[len] > max) {
        max = arr[len];
      }
    }
    return max;
}

source: Find the min/max element of an Array in JavaScript

It really works really well and very fast. I've got a question (out of curiosity). When I tried to add (or manipulate) something, the result didn't match based from the first code. Here is the code:

var points = [30,100];
document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
    var len = arr.length;
    var max = -Infinity;
    while (len--) {
      if (arr[len-1] > max) {
        max = arr[len-1];
      }
    }
    return max;
}

I've assumed that the array[0] is the first array element, also I used post-decrement function, and yet I didn't get the expected result.

Niche
  • 967
  • 5
  • 23
ExCode
  • 11
  • 4
  • 1
    What will happen on the last round (`len === 0`) in your modified example? – Andreas Nov 02 '18 at 16:00
  • Take note that you also can use the builtin `Math.max` like this: `Math.max.apply(null, [30, 100])` – Simon Zyx Nov 02 '18 at 16:20
  • 1
    Using `Infinitie` is a generally bad practice. let's assume that first iteratebale value match our condition best `var max = arr[arr.length-1]` – qiAlex Nov 02 '18 at 16:25

2 Answers2

1

First of all, using arr[len-1] adds a new problem to the mix: Index out of bounds. This happens when the loop iterates the last element in the loop (len == 0 after len--) and you end up looking for arr[-1] which doesn't exist. Also, you're not checking anymore for the last index in the array (arr[arr.length - 1]), since len-- already substracts from the index. Like so:

var points = [30,100];
document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
    var len = arr.length; // len == 2
    var max = -Infinity;
    while (len--) { // len == 1
      // checking for arr[len - 1] the first time
      // results in checking for arr[0]. arr[1] will be skipped
      if (arr[len-1] > max) { 
        max = arr[len-1];
      }
    }
    return max;
}

The function works well in the first place, so... Why fix what isn't broken?

Check out arithmetic operators for more info on len--.

Niche
  • 967
  • 5
  • 23
  • Yes, but the while condition also substracts 1 from `len`'s value. Check out [arithmetic operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Arithmetic_operators) – Niche Nov 02 '18 at 16:13
  • Based on my observation: When it enters in while loop, the initial value of len is 2. The condition is accepted and proceeds in if statement. When I used len-1, it should direct in arr[1]=100 not 30. When the value finished storing the value in var max, the len will be deducted and repeats the while loop. May I know why it bypasses the if (arr[1] > max) or was my understanding in using the while loop is wrong ? Thanks for answering my question. – ExCode Nov 02 '18 at 16:17
  • The initial value of `len` is 2. Then the `while` condition comes and evaluates ([and operates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Arithmetic_operators)) upon `len--`. Now `len`'s value is 1. Now, on the first iteration, checking for `arr[len-1]` will go to the `0` position of your array. – Niche Nov 02 '18 at 16:20
  • Saying `len--` is the same as saying `len -= 1` – Niche Nov 02 '18 at 16:23
  • I see. I thought that it is a post-decrement, not a standard arithmetic operator. Thank you very much. – ExCode Nov 02 '18 at 16:25
  • It operates right after evaluating the variable. For instance: `let num = 10; console.log(num-- + num--);` will output `19`. – Niche Nov 02 '18 at 16:28
  • I see. I assumed that the len-- is a post-decrement, when in reality, it is a standard arithmetic operator. Thank you very much. – ExCode Nov 02 '18 at 16:30
  • It is, but it decrements *right after* evaluating the variable. In a similar manner, `--len` decrements *right before* evaluating, such that, in the example above, `let num = 10; console.log(num-- + --num);` outputs `18`. – Niche Nov 02 '18 at 16:32
  • I see. I'm still learning to code and I'll add this to my notes. Thanks for helping me. – ExCode Nov 02 '18 at 16:36
  • For further reference, you can read `len--` as 'Evaluate `len` and substract 1', and `--len` as 'Substract 1 and evaluate `len`' – Niche Nov 02 '18 at 16:39
0
function myArrayMax(arr) {
var len = arr.length;
var max = -Infinity;
while (len--) { // here itself you are decrementing the value of len
  if (arr[len-1] > max) { // here also you are checking the previous one. Then you won't get chance to check the last array element.
    max = arr[len-1];
  }
}
return max;
}

// moreover you will get index out of bound exception while going in last iteration.