Dont understand the output from lesson 7- Victory


#1


I passed the lesson, but it outputs a "?" as the response. I am just wondering what is the proper output and why did it print the way it did?


/*jshint multistr:true */

var text = "How is my best friend James pocket shark doing this 
afternoon pocket shark James?"

var myName = "James"

var hits= []

for(var i = 0; i < text.length; i++)
if (text[i]==="J"){
    for (var j = i; j < (i + myName.length); j++)
    hits.push(text[j])
    console.log(text[j])
}


#2

@blogmaster71010

You have the "?" attached to "James"...

That's why it is part of the array because you didn't put space between it so it consider it like a character of your name.


#3

Thank you for responding, when I take off the ?, I get an "undefined" response, which also gets the pass, but I am sure that isnt what the lesson was seeking.


#4

@blogmaster71010

This course shows you how to enter every character of your name in an array by using for loops and if statement.


#5

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. hits.push();, console.log();) is a best practice.


Does this help?

frisby


#6

Hi James,

I explained the reason for this below, but I believe you get undefined when you remove the question mark because for whatever reason (that I don't know), your program wants to print one character past your name to the console. If you remove ? there are no additional characters, hence the console says the space after James is undefined. Does that make sense?

frisby