Reputation: 85
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 '));
Upvotes: 0
Views: 47
Reputation: 13623
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:
trim(' hello ')
.if
condition is met-- string is sliced and trim('hello ')
is called.if
condition is met-- string is trim('hello')
is called.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.
Upvotes: 4
Reputation: 793
You are returning your str
only on else
clause. You have to return in every case:
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);
}
return str;
}
Upvotes: 0