I was solving some JS challenges and noticed that when using arrow function the result es 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
You can use My Plunker here
I was solving some JS challenges and noticed that when using arrow function the result es 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
You can use My Plunker here
Share Improve this question asked Mar 18, 2017 at 22:52 shireef khatabshireef khatab 1,0052 gold badges18 silver badges33 bronze badges 2- 1 if I remember the spec correctly, one line arrow functions return whatever that line is. Regular functions don't do that by default – Jhecht Commented Mar 18, 2017 at 22:54
-
1-line arrow functions implicitly
return
the line - regular functions need explicitreturn
– hackerrdave Commented Mar 18, 2017 at 22:58
2 Answers
Reset to default 6You 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"));
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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742323084a4422206.html
评论列表(0条)