Skip to content

Instantly share code, notes, and snippets.

@leahgarrett
Created May 28, 2019 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leahgarrett/5d0056e25b98298faa9253146726bd7e to your computer and use it in GitHub Desktop.
Save leahgarrett/5d0056e25b98298faa9253146726bd7e to your computer and use it in GitHub Desktop.
Call Stack

Callstack

A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.

  • When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function.
  • Any functions that are called by that function are added to the call stack further up, and run where their calls are reached.
  • When the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing.
  • If the stack takes up more space than it had assigned to it, it results in a "stack overflow" error. https://developer.mozilla.org/en-US/docs/Glossary/Call_stack

The call stack is how JavaScript keeps track of the execution order of its code. You can either push onto the call stack or pop off the top.


We often see callstack when something has gone wrong.

Leahs-MacBook-Pro:sample-code leahgarrett$ node sandbox.js 
/Users/leahgarrett/Documents/ca/coderacademy-notes/sample-code/sandbox.js:2
    console.trace(`\n\n\nSTART of formatString ${value}`)
                                                 ^

ReferenceError: value is not defined
    at formatString (/Users/leahgarrett/Documents/ca/coderacademy-notes/sample-code/sandbox.js:2:50)
    at Object.<anonymous> (/Users/leahgarrett/Documents/ca/coderacademy-notes/sample-code/sandbox.js:12:16)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:266:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:596:3)

Nested function example

As you could see as the code runs it is placed on the call stack. Once the code has finished executing it pops off the top.

const REQUIRED_LENGTH = 10;
function checkLength(aString) {
    console.trace(`Inside of checkLength ${aString}`)
    return aString < REQUIRED_LENGTH;
}

function fixLength(aString) {
    if (!checkLength(aString)){
        return aString.padStart(REQUIRED_LENGTH, '*');
    }
    return aString;
}

function formatString(aString){
    console.trace(`\n\n\nSTART of formatString ${aString}`)
    
    let formattedString = aString[0].toUpperCase() + aString.slice(1).toLowerCase();
    
    formattedString = fixLength(formattedString);

    return formattedString;
}

console.trace(`Before calling formatString`)
const result = formatString('this is a test');
console.trace(`After calling formatString`)
console.log(result);

Simple recursion example

function recursionTest(value){
    if (value < 10) {
        console.trace(`\n\n\nSTART of loop ${value}`)
        value++;
        recursionTest(value);
    }
    
    console.trace(`END of loop ${value}`)
}

recursionTest(3);

Challenge

Using console.trace to explore recursion (Code and background information

Implement the follow as a console app:

function factorial(x) {
  if (x < 0) return;
  if (x === 0) return 1;
  return x * factorial(x - 1);
}
factorial(3);
// factorial(5);
// factorial(7);

Add a counter to count how many times the function is executed Add console.trace statement that shows the counter Write code to execute the function and show the counter value

Implement the follow as a console app:

function revStr(str){
  if (str === '') return '';
  return revStr(str.substr(1)) + str[0];
}
revStr('cat');
// revStr('mouse');
// revStr('javascript');

Add a counter to count how many times the function is executed Add console.trace statement that shows the counter Write code to execute the function and show the counter value

Beast

Fibonaci can be solved using recursion or iteration.

Re-write the following two methods in javascript: (Code and background information

fibonacciRecursion

    public static int fibonacciRecursion(int nthNumber) {
        if (nthNumber == 0) {
            return 0;
        } else if (nthNumber == 1) {
            return 1;
        }   
        return fibonacciRecursion(nthNumber - 1) + fibonacciRecursion(nthNumber - 2);
    }

fibonacciLoop

    public static int fibonacciLoop(int nthNumber) {
        int previouspreviousNumber, previousNumber = 0, currentNumber = 1;

        for (int i = 1; i < nthNumber ; i++) {
            previouspreviousNumber = previousNumber;
            previousNumber = currentNumber;
            currentNumber = previouspreviousNumber + previousNumber;
        }
        return currentNumber;
    }

Add a counter to count how many times each is executed Add console.trace statements to each function that shows the counter Write code to execute each function and show the counter values for each

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment