Reputation: 1005
I was solving some JS challenges and noticed that when using arrow function the result comes as expected, when i try same code using normal function it doesn't. Can someone explain the difference or i might have a typo!!
here is the first solution (works):
function titleCase(str) {
str = str.split(' ').map(i => i[0].toUpperCase() + i.substr(1).toLowerCase()).join(' ')
return str;
}
console.log(titleCase("I'm a liTTle tea pot")); // I'm A Little Tea Pot
And the second solution with normal function (returns empty string):
function titleCase2(str) {
str = str.split(' ').map(function(i, index){ i[0].toUpperCase() + i.substr(1).toLowerCase()}).join(' ')
return str;
}
console.log(titleCase2("I'm a liTTle tea pot")); // empty string
Upvotes: 3
Views: 6173
Reputation: 41893
You miss a return
keyword inside the callback function.
Fat-arrow function returns a value by default, the return
keyword is built-in. To get the value from the normal function expression, you have to return it.
function titleCase2(str) {
str = str.split(' ').map(function(i, index) {
return i[0].toUpperCase() + i.substr(1).toLowerCase()
}).join(' ')
return str;
}
console.log(titleCase2("I'm a liTTle tea pot"));
Upvotes: 6
Reputation: 6706
You need explicit return
for non-arrow functions. 1-line arrow functions implicitly return the result of that one line.
function titleCase2(str) {
return str.split(' ').map(function(i, index){ return i[0].toUpperCase() + i.substr(1).toLowerCase()}).join(' ')
}
console.log(titleCase2("I'm a liTTle tea pot")); // I'm A Little Tea Pot
Upvotes: 0