Ttile case a sentence challange, curious about specific jscript behaviour [SOLVED]

while doing this challenge i discovered a javascript behaviour i just cant understand, why does this function return the help value and not str??

function titleCase(str) {
var help = [];  
str=str.split(" ");
  help = str;
   return str ;
titleCase("I'm a little tea pot");

Firstly, you need to use triple backticks to post code on the forum. See here for more details.

The next thing is that on the line help = str, you are assigning an array to another variable. To the best of my knowledge, an array in JavaScript is treated as an object. Which means you pass by reference rather than by value.

This means that what you are doing, essentially, is pointing two separate variables to the same array. So any changes made to one are reflected in the other.

Use var help = str.slice(). This will clone the array and return a reference to the new array. See this StackOverflow answer for more info.

1 Like

It is returning str…
str.split() returns an array, so when you wrote str=str.split(" "); your variable str became an array of strings. If you want to return a string, you’ll have to use the join method on the array.
Edit: Sorry, I misunderstood the question… I thought you were wondering why it was returning an array vs a string rather than why the contents of the array were different than what you expected.

I just reread my reply, and that may not make a whole lot of sense if the subject was unclear to begin with… I wrote a blog post on this challenge that covers it pretty deeply, including the JavaScript methods needed… Check it out if you have more questions.

thx, didnt know that arrays are treated as objects, makes perfectly sense now.