Step 5. Pass, but doesn't print what it should


#1



https://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/5?curriculum_id=506324b3a7dffd00020bf661#


It prints '12' instead of 'brad' 3 times...
Or am i getting confused here...?


/*jshint multistr:true */

var text = "chicken, pot, pie, brad, fish, kettle, book, brad";
var myName = "brad";
var hits = [];

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



#2

There are no console.log()'s, so why should it print anything?


#3

Okay thanks. my bad.
Adding
console.log(hits) prints it with commas.. What am i missing/completely oblivious too?


#4

You could use join(), to put it together nicely.


#5

Sorry for 20 questions, fairly new (hence the lessons) - where would I add join()?


#6

Join usage:

http://www.w3schools.com/jsref/jsref_join.asp


#7

Okay thats not very descriptive - although I tried implementing it..

/*jshint multistr:true */

var text = "chicken, pot, pie, Brad, fish, kettle, book, Brad";
var myName = "Brad";
var hits = [];
var print = myName.join(" "); //** I also tried text.join - but says text.join is undefined?

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

#8

Ok first of all as @cadecodes mentioned you forgot the console.log in your first try. So the reason you see anything is that the console always echoes the last value unless it is undefined (e.g. console.log has no value, undefined). So here the last value is the value of your push statement. And if you google javaScript push you might find this:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

Returns
The new length property of the object upon which the method was called.

So as you're name has a length of 4 and it occurs 3 times, 12 should be reasonable.

Also that hits prints letter by letter with ,s in between is ok, because you push it letter by letter to the hits array. And for an example of the join method:

console.log(hits.join(""))

What happens there is that you build a string by adding the entries of your array with the separator mentioned in the () of join:

    ["b","r","a","d","b","r","a","d","b","r","a","d"].join("") 
    -> "b"+""+"r"+""+"a"+""+"d"+""+ "b"+""+"r"+""+"a"+""+"d"+""+"b"+""+"r"+""+"a"+""+"d"
    -> "bradbradbrad"

#9

Hi @haxor789,

Thanks for your reply, much apprecaited and thanks for spelling it out for an utter begginner.
I see what I was missing now. Thanks for dyour detailed response :).

And thanks @cadecodes - I believe a more descriptive answer in the beginning would've been alot more helpful, but again thanks for your time in answering my question.

Thanks!


#10