Tell us what’s happening:
At the risk of sounding dumb, could someone explain where my code goes wrong?
Your code so far
function sentensify(str) {
// Add your code below this line
str.split(/\W/);
str.join();
return str;
// Add your code above this line
}
sentensify("May-the-force-be-with-you");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36.
Challenge: Combine an Array into a String Using the join Method
Is that to suggest that what I am currently doing is only effective if I’m working on mutable items?
Also, I noticed it’s possible to chain multiple methods like split, join, reduce, etc on the same variable but have a line separating each method for ease of readability? I tried doing something similar and couldn’t get it to work.
As @camperextraordinaire suggested, split and join return a new value, and DO NOT mutate the original input:
this means:
var s = 'Batman, Batman';
const splitted = s.split(', ') // works
console.log(s) // 'Batman, Batman'
console.log(splitted) // [ 'Batman', 'Batman' ]
So the original s is still unchanged, meaning the the next line of code:
s.join() // TypeError: s.join is not a function
will fail since string don’t have a join method.
When you chain multiple methods, you are calling the next function on the previous returned value, with the caveats that the first method must be on the same line, otherwise the JS interpreter won’t understand if you are declaring a new variable or doing something:
var someHtmlElement // you are declatrig a new undefined variable
.changeColor()
.changeSize()
.changeContent()
However this is a practice that I personally discourage, I find it error-prone, bug prone and hard to debug.
And I can hardly see the advantage over the more verbose version
const withColor = changeColor(prevHtml)
const withSize = changeSize(withColor) // <-- pass the return of the previous call
const someHtmlElement = changeContent(withSize) // both with color and size
I meant the habit of chaining methods, I personally don’t like it that much, and I have found in my experience that it often causes me more errors that benefit.
But this is a totally biased opinion made by my own experience
I find chained methods easier to read. But I usually write code with all the intermediate variables and then after everything works I chain things - much easier to debug
@Jengas2015, for me also it seems little bit confusion. What i did is to declare the variables before join.
function sentensify(str) {
// Add your code below this line
var myarray = str.split(/\W/); //this splits it by - this and my array is now `["May", "the", "force", "be", "with", "you"]
var result = myarray.join(" ");` and this joins the array by spaces and make string again. and the value of variable result is now "May the force be with you"
return result;
}