Return value from within a recursive function

Assume that you want to want to create a square function recursively.

Example:

javascript
var res = 0

const square = (n, start, total) => {

    if(n !== start){

        total = total * 2
        square(n, start + 1, total)

    }
    else{

        res = total

    } 

}

square(5, 0, 1)

console.log(res) // 32

Imagine that rather than declaring a global variable, you want to return the result from within the function.

Example:

javascript
let res = square(5, 0, 1) 

console.log(res)// 32

How would you code the function?.

Example:

javascript
const square = (n, start, total) => {

    let res = 0

    if(n !== start){

        total = total * 2
        res = square(n, start + 1, total)

    }
    else{

        res = total

    }

    return res

}

let res = square(5, 0, 1)

console.log(res) // 32

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.