I just came across one thing and I cannot find an answer why is this happening so maybe someone can help.
This is the piece of code
function titleCase(str) {
let arr = str.split(" ")
.map(s => s.charAt(0).toUpperCase() + s.substring(1).toLowerCase())
console.log('arr1', arr)
let arr2 = str.split(" ")
arr2.map(s => s.charAt(0).toUpperCase() + s.substring(1).toLowerCase())
console.log('arr2', arr2)
}
titleCase("I'm a little tea pot");
I am interested in why arr1 (when map is chained immediately after split is working as expected. It returns ["I'm", "A", "Little", "Tea", "Pot"], but arr2 is returning ["I'm", "a", "little", "tea", "pot"]
Should this type of writing (whether it is chained or not) return the same key? What am I missing?
.mapreturns a new array, it doesn't mutate the original. Soarr2.map()just does something and throws away the result.arr. In the second case you don't retain the result of the.map..mapreturns a new array. If you don't save it, then you will not have it. It's similar as havingstr2 = "hello" + "world"and just"hello" + "world"by itself. A new string will be constructed but never saved. Same with.map- a new array is created and never saved.