1

Sorry, I am new to javascript and i'm just trying to get my feet wet.

I have used join()in the past without problems, but for some reason this join seems to return a blank string.

The information in myArray seems to be formatted correctly.

any help would be much appreciated. Thanks!

  function titleCase(str) {
  var splitArray = str.split(" ");
  var myArray = [];
  var joinArray = myArray.join(' ');

  for (var i in splitArray) {
    myArray.push(splitArray[i].charAt(0).toUpperCase() + splitArray[i].slice(1).toLowerCase());
  }

  return joinArray;
}

titleCase("capitalize the first letter of each word in this string");
1
  • 1
    You're returning joinArray, which is created at a time myArray is empty. You can assign a joined array after the loop, or just return myArray.join(' '). Commented Dec 15, 2015 at 17:48

3 Answers 3

2

You were joining myArray before it had anything in it, and then returning it, unmodified.

  function titleCase(str) {
    var splitArray = str.split(" ");
    var myArray = [];

    for (var i in splitArray) {
      myArray.push(splitArray[i].charAt(0).toUpperCase() + splitArray[i].slice(1).toLowerCase());
    }

    return myArray.join(' ');
  }

document.getElementById('result').innerHTML = titleCase("capitalize the first letter of each word in this string");
<p id="result"></p>

Sign up to request clarification or add additional context in comments.

Comments

1

You're defining joinArray before myArray has been filled. Try moving

var joinArray = myArray.join(' '); 

to the line before

return joinArray;

2 Comments

Thanks. that makes a lot of sense now
No problem, happy to help.
1

I figured it out. Apparently position matters and the join was happening before the for loop had a chance to run.

1 Comment

Please mark one of the answers above as the answer (whichever you found more useful) instead of reiterating.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.