Finding that Special Someone


#1


https://www.codecademy.com/courses/building-an-address-book/0/5?curriculum_id=506324b3a7dffd00020bf661


I doesn't come up with any error messages, but just say "way to go" and then I can continue to next lesson. But it prints out both Bob Jones and Mary Johnson. Isn't it supposed to just print out Bob Jones?


var contacts = [bob, mary];

function printPerson(person) {
    console.log(person.firstName + " " + person.lastName);
}

function list() {
	var contactsLength = contacts.length;
	for (var i = 0; i < contactsLength; i++) {
		printPerson(contacts[i]);
	}
}

/*Create a search function
then call it passing "Jones"*/
var search = function(lastName) {
    var contactsLength = contacts.length;
    for (var i = 0; i < contactsLength; i++) {
        if (this.lastName = lastName) {
            printPerson(contacts[i]);   
        }
    }
}
search("Jones");

Thanks! :sunglasses:


#2

There is a problem with this line:

if (this.lastName = lastName)

The "=" in JavaScript is the assignment operator, not a comparison operator.
The comparison operator in JS is "===".


#3

If I change this to if (this.lastName === lastName) instead, it will come up with the error: It looks like your search function didn't log "Bob Jones" to the console. Did you remember to call search after you defined it?.


#4

What is "this" referring to in that line of code?
Don't you mean to be comparing the lastName to the lastName of an element in the contacts array? (Recall that this is inside a for loop where 'i' is your counter variable....)


#5

Just a wee tiny footnote on this :slight_smile:

Javascript has the ability to actually compare at two levels.
In the first if you use "===" you are actually comparing both the value and the type.
However you can also use "==" which only compares the value.

Just 2 little gnomes worth of tidbit info :slight_smile:


#6

Hi @stef_nielson,

It looks like you might be missing some code :slight_smile:
If you still require any assistance with this if you could please post the entirety of the code you are using in your lesson we could be sure there isn't anything else at play.
Otherwise @megaplayer47736 is right on the ball here :slight_smile:

Please see the code sample below. But the focus should be not only on the comparison operator but also what is being compared. It seems like you've pretty much got this down so the sample is only a partial snippet.

/*Create a search function
then call it passing "Jones"*/
var search = function(lastName) {
    var contactsLength = contacts.length;
    for (var i = 0; i < contactsLength; i++) {
        if (contacts[i].lastName == lastName) { //lets compare on the actual indexed value we want and use the compare operator
            printPerson(contacts[i]);   
        }
    }
}
search("Jones");

`


#7

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