DEV Community

Code_Regina
Code_Regina

Posted on

Recursion

                   -Why use Recursion
                   -The Call Stack 
                   -Helper Method Recursion
Enter fullscreen mode Exit fullscreen mode

Why use Recursion

There is another opportunity to create repetition in programs without using loops. Recursion makes it possible to do so because it's a process where a function calls itself over and over again.

Alt Text

The Call Stack

The call stack is stack data structure. Any time a function is invoked it is placed or pushed on the top of the call stack.
When JavaScript sees the return keyword or when the function ends, the complier will remove or pop off.

Call stack example


function takeShower(){
    return "Showering!"
}

function eatBreakfast(){
    let meal = cookFood()
    return `Eating ${meal}`
}

function cookFood(){
    let items = ["Oatmeal", "Eggs", "Protein Shake"]
    return items[Math.floor(Math.random()*items.length)];
}
function wakeUp() {
    takeShower()
    eatBreakfast()
    console.log("Ok ready to go to work!")
}

wakeUp()

Enter fullscreen mode Exit fullscreen mode

function countDown(num){
    if(num <= 0) {
        console.log("All done!");
        return;
    }
    console.log(num);
    num--;
    countDown(num);
}
countDown(3)

// Iterative Version
function countDown(num){
    for(var i = num; i > 0; i--){
        console.log(i);
    }
    console.log("All done!")
}

Enter fullscreen mode Exit fullscreen mode

Helper Method Recursion


function collectOddValues(arr){

    let result = [];

    function helper(helperInput){
        if(helperInput.length === 0) {
            return;
        }

        if(helperInput[0] % 2 !== 0){
            result.push(helperInput[0])
        }

        helper(helperInput.slice(1))
    }

    helper(arr)

    return result;
}

collectOddValues([1,2,3,4,5,6,7,8,9])

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
luisguillermobultetibles profile image
luisguillermobultetibles

He escuchado que existe un isomorfismo entre la recursión y la repetición.