Search code examples
javascriptreturnundefined

my DIY trim function cannot return correct answer, it returns undefied


I am trying to create a function named "trim" to delete the blanks at the head and the tail of an input string. (I know String.prototype.trim can do the same work, I'm just practicing my JS) but it return "undefined",can you help me?

function trim(str) {
    if (str.charAt(0) === ' ') {
        str = str.slice(1);
        trim(str);
    } else if (str.charAt(str.length - 1) === ' ') {
        str = str.slice(0, -1);
        trim(str);
    } else {
        return str;
    }
}

console.log(trim('  ab c '));


Solution

  • You need to return from every place you are recursing, in order to make sure that you have returns all the way back up the stack to the original caller. See the snippet below.

    function trim(str) {
        if (str.charAt(0) === ' ') {
            str = str.slice(1);
            return trim(str);
        } else if (str.charAt(str.length - 1) === ' ') {
            str = str.slice(0, -1);
            return trim(str);
        } else {
            return str;
        }
    }
    
    console.log(trim('  ab c '));

    Some more context:

    Every time you call trim from inside the body of the trim function, you are recursing. If you take the string ' hello ' and call trim as (trim(' hello ')), the following occurs:

    1. Call trim(' hello ').
    2. First if condition is met-- string is sliced and trim('hello ') is called.
    3. Second if condition is met-- string is trim('hello') is called.
    4. No if condition is met-- else block is entered ` 'hello' is returned.

    So our call stack is trim(' hello ') ==> trim('hello ') ==> trim('hello'). However, in the function as you originally wrote it, only the last call to trim (trim('hello')) actually returns a value to the previous caller-- the other invocations of trim return nothing (undefined). In order to make sure that the value return is passed all the way back up to the original caller of trim(' hello '), you need to make sure that every time you recurse you return the result of the recursion.