That’s interesting, I don’t know why it prints the question mark at all to begin with.
However, if you add a second
console.log(text[j]); before your
push, you’ll see that the letters
pushed are indeed
J, a, m, e, s, J, a, m, e, s as intended. As well, if you add a
console.log(hits); at the end of your program, you should get the desired [J,a,m,e,s,J,a,m,e,s] printout. (This is the “proper output” you asked about.)
So basically, it looks like the program will
push the letters of your name to the array until the correct length has been added, but then print the following character after it’s done
pushing for some reason (I believe it does this after the first instance of
James too, but because it’s a space it’s not noticeable).
At first, I couldn’t figure out why your program would behave differently when adding a
console.log(text[j]); to the same place in the example program doesn’t have this, ahem, bonus. But then I realized none of your
for statements have curly brackets.
I didn’t do a walkthrough to see how this affects the program, because frankly I don’t know how a bracketless for loop would behave (does it consider itself closed? Then why do we still get the same letters added to the array?), but if you add brackets to the appropriate places it should resolve this issue.
Also, perhaps someone more experienced can weigh in, but I believe I read that remembering semicolons where appropriate (e.g.
console.log();) is a best practice.
Does this help?