Code to find the center of an array without using ES6 functions - JavaScript

We are required to write an array function midElement() that returns the middlemost element of the array without accessing its length property and without using any kind of built-in loops.

If the array contains an odd number of elements, we return the one middlemost element, or if the array contains an even number of elements, we return an array of two middlemost elements.

How It Works

The solution uses recursion to count array elements by incrementing an index until reaching undefined, then calculates the middle position(s) based on whether the count is odd or even.

Example

Following is the code −

const arr = [14, 32, 36, 42, 45, 66, 87];
const array = [13, 92, 83, 74, 55, 46, 74, 82];

const midElement = (arr, ind = 0) => {
    if(arr[ind]){
        return midElement(arr, ++ind);
    };
    return ind % 2 !== 0 ? [arr[(ind-1) / 2]] : [arr[(ind/2)-1], arr[ind/2]];
};

console.log(midElement(arr));
console.log(midElement(array));

Output

This will produce the following output in console −

[ 42 ]
[ 74, 55 ]

Step-by-Step Breakdown

Let's trace through how the function works:

const testArray = [1, 2, 3, 4, 5];

// Step 1: Count elements recursively
const midElement = (arr, ind = 0) => {
    console.log(`Checking index ${ind}: ${arr[ind]}`);
    
    if(arr[ind]){
        return midElement(arr, ++ind);
    };
    
    console.log(`Total elements found: ${ind}`);
    
    // Step 2: Calculate middle based on odd/even count
    if(ind % 2 !== 0) {
        console.log(`Odd count: returning element at index ${(ind-1)/2}`);
        return [arr[(ind-1) / 2]];
    } else {
        console.log(`Even count: returning elements at indices ${(ind/2)-1} and ${ind/2}`);
        return [arr[(ind/2)-1], arr[ind/2]];
    }
};

console.log("Result:", midElement(testArray));
Checking index 0: 1
Checking index 1: 2
Checking index 2: 3
Checking index 3: 4
Checking index 4: 5
Checking index 5: undefined
Total elements found: 5
Odd count: returning element at index 2
Result: [ 3 ]

Key Points

  • The function uses recursion to count elements without accessing the length property
  • For odd-length arrays, returns the single middle element in an array
  • For even-length arrays, returns the two middle elements
  • No ES6 features or built-in loops are used

Conclusion

This recursive approach cleverly counts array elements by iterating until undefined, then calculates middle positions mathematically. It successfully finds the center without using length property or built-in loops.

Updated on: 2026-03-15T23:18:59+05:30

372 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements