Please help I dont understand .push()


#1


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


Hi , The code below runs correctly. However in need help with understanding the "hits.push()" part . I am afraid i do not understand WHY. I need help understanding what the line of code is meant to do. I know the HOW from looking at the example from the start of this exercise.

In other words whats up with this line of code???

var text = "The most common way that happens is for the HTML page to show form Benjamin elements (like text boxes) Benjamin to a user that they Benjamin can type into, and then Benjamin using JS to read those values into your program's variables."
var myName = "Benjamin"
var hits = [];
for(letter = 0; letter<text.length; letter++){
    if(text[letter] === "B"){
        for(actualName = letter; actualName<letter+myName.length; actualName++){
            hits.push(text[actualName]);
        }
    }
}


#2

you took a variable named hits and empty array in it.

var hits = [];  //empty array
hits.push(text[actualName]); //adding new value to the end of the array

The push() method is adding value into the array.

example:

var i=[]; //empty array

i.push("good","better","best")  // push() method

console.log(i) // prints all items

console.log(i[2]) // ptints only 3rd items[array index starts from 0 ]

Hope you've understand :slight_smile:


#3

Thanks! now i get it


#4

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