Title Case a Sentence - i is not defined?

Tell us what’s happening:

I think the code is fine (runs in vscode where I wrote it), but I keep getting “i is not defined” ??? I tried retyping it and still get nothing. is this a glitch or am I missing something?

Your code so far


function titleCase(str) {
    let strNew = str.toLowerCase().split(' ');
    let newArray = [];
    for (i = 0; i < strNew.length; i++) {
        newArray.push(strNew[i].charAt(0).toUpperCase() + strNew[i].slice(1));
    }
    return newArray.join(" ");
    
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36.

Link to the challenge:( had to change link for forum)
fcc/.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence/

You need to define i before you use it in the for loop. For example, you have:

for (i = 0; i < strNew.length; i++) {
    newArray.push(strNew[i].charAt(0).toUpperCase() + strNew[i].slice(1));
}

But you should have:

for (let i = 0; i < strNew.length; i++) {
    newArray.push(strNew[i].charAt(0).toUpperCase() + strNew[i].slice(1));
}

AHHHHHHH - wow.

Thank you :raised_hands:

1 Like

For anyone who might run across this -

The reason my initial code ran in VSC and not in the FCC console, is because I wasn’t in strict mode and ‘i’ was assigned to global ‘window’ variable. FCC console is always in strict mode so it popped an error.

1 Like