For loop help - total newbie!

Hi,

I’m unsure why my answer produces undefined + answer im looking for.

    let array = string.toLowerCase().split(" ");
    let word;

    for (let i = 0; i < array.length; i++){
      word += array[i].charAt(0).toUpperCase() + array[i].slice(1);
      
    }
    
    return word; 

    }

console.log(camelize("Javascript is great"))

Whereas this produces the correct answer:

function camelize (string){
    
    
    
    let array = string.toLowerCase().split(" ");
    let word;

    for (let i = 0; i < array.length; i++){
      array[i] = array[i].charAt(0).toUpperCase() + array[i].slice(1);
      
    }
    
    return array.join(""); 

    }
    

console.log(camelize("Javascript is great"))

I have not really seen variable[i] = …
online variable += … where the result is continually added to the variable.

Please can someone explain why when you do this the first thing in the list is undefined.

Thank you for your help!

You never initialized word

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Thank you.

I always assumed let word & let word = “” was the same thing.

now i know!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.