Is my way of solving these things bad?

Is my way of solving these things bad?
0

Tell us what’s happening:
Ok so this has happerned in one way or another for most of the questions in this set, after ive finished i go though the hints to see the differnce between my code and the soulation and they always look tottaly differnt generally im writing more code using more if/for loops and using less methods i understand javascript is a high level lang so i should probley be trying to make use of these methods more below is the last question im doing for the weekend it passes all there criteia but is differnt than the answer given but with more code and more mess so i guess its not as good as there answer however does that make it bad or is it ok to be solving these like the way i did below

Your code so far


function titleCase(str) {

let startString = str.toLowerCase();

let array = startString.split(" ")

//console.log(array)
let newString = ""
let fin = ""
  for (let i = 0 ; i < array.length ; i++){
    //console.log(array[i])
    let low = array[i][0] 
    let up = low.toUpperCase();
 newString =  array[i].replace(array[i][0], up);

   console.log(i)
 //  console.log(newString)
 if (i < array.length-1){
   newString += " "
   fin += newString

  } else {
    fin += newString
  }
  }
  console.log(fin)
  return fin;
}

titleCase("I'm a little tea pot");



//

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence

First of all, I think it’s important to realize that any solution is a good solution. I.e. if you managed to solve the problem using your own code (without the FCC editor timing out) you did well.

That being said, what you’ve realized is true and generally you can look at it this way: more loops than necessary will make your program run slower - if that makes a huge difference or not depends on the program. More if statements means that your code is less readable.

What I’d suggest you do - but only after you’ve solved the problem in your own way - is to refactor your code. Have a look through your solution and have a JavaScript documentation site up in a tab. Is there anything that could be replaced with a pre-defined function? Could you reduce the amount of variables you’re using? An example in your code above is how you convert a letter to uppercase:

let low = array[i][0]
let up = low.toUpperCase();

Do you really need to define that ‘up’ variabel or can you move the .toUpperCase()-function to the line above?

3 Likes