Qaqli
Qaqli

Reputation: 199

How does this conditional statement work?

This function finds the middle value of an array. But the conditional statement makes no sense to me, since arr.length === 0 is never true but the function still works for both even and odd numbers. I think the condition should be arr.length % 2 !== 0 and it works too, but even then I don't see how the correct value is returned, since for an array of 1-13, the function would return the Math.floor of 13/2 = 6.5 which is 6, but it returns 7. And for an array 1-12 it would return the Math.ceil of (12-1)/2 = 5.5 which is also 6, but again it returns 7, which is what it's supposed to do but I don't see how the conditional statements produce this result.

let x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
// if even, the number closer to end is returned

function findMiddle(arr) {
   return arr.length === 0 ? arr[Math.floor(arr.length / 2)]
   : arr[Math.ceil((arr.length - 1) / 2)];
}

console.log(findMiddle(x))

Upvotes: 1

Views: 111

Answers (2)

Ikdemm
Ikdemm

Reputation: 2353

Since the condition is always false, this function will always return the first value which is arr[Math.ceil((arr.length - 1) / 2)] which is always correct I assume.

  • For the first example (an array from 1 - 13): arr.length is 13, arr.length / 2 will be 6.5, then Math.ceil(arr.length / 2) will be 7 and finally arr[Math.ceil(arr.length / 2)] will result in arr[7] which is 8
  • For the second example (an array from 1 - 12): arr.length is 12, arr.length / 2 will be 6, then Math.ceil(arr.length / 2) will be 6 and finally arr[Math.ceil(arr.length / 2)] will result in arr[6] which is 7.

Conclusion: The condition is not doing anything there. It's completely useless if you always provide it with non-empty arrays. Your function, in that case, will be simply:

function findMiddle(arr) {
   return arr[Math.ceil(arr.length / 2)]
}

And it will give the same results.

Upvotes: 1

fafl
fafl

Reputation: 7385

If arr has no elements, this function returns arr[0] which does not exist, so it throws an error. (edit: this would happen in any other language, but javascript being javascript actually returns undefined)

For an even number of elements, it returns the second of the two middle-elements.

For an uneven number of elements it returns the middle one.

In your example, it returns the element at index 6. This element is has the value 7.

Upvotes: 0

Related Questions