6 and 7 Need for/in clarity


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-3bmfN/0/7?curriculum_id=506324b3a7dffd00020bf661#


Ok so I got it to list all and to search name steve (Sourced from other forum threads). But I am unclear of the use of for/in. Like we have a function(steve) and we have for(allNames in friends)
Does that make function(steve) = allNames?.

Asking because the exercise asks me to search for a particular name, which I choose to be steve. But I find the above explanation to be the only relationship/pattern that I can see.


//
var search = function(friends) {
    // Do something here
};
//
var friends = {
    bill:{firstName: "Bill", lastName: "Cosby", number: "69-80085-69", address:["69 Pickadelly road" ,"Bullsville", "6969"]},
    steve:{firstName: "Steve", lastName: "Irwin", number: "90909-09090-90", address:["89 Dickadelly road" ,"Dullsville", "4969"]}  
};

var list = function(friends) {
    for(var allNames in friends) {
        console.log(allNames,"test!!!!!!!!!!!!!!!!")
        console.log(allNames)
        console.log(friends[allNames])
    }
};
//list()

var search = function() {  //function of allNames is function()?
    for(allNames in friends) {  //cant declare same variable in 2 different processes
        if(friends[allNames].firstName === "Steve") {
            //console.log(friends[allNames]);
            return friends[allNames];
        }
    }
};
search("steve")


#2

See, if you just copy the post from another topic, you are not learning it. Your choice.

what? No, the function is called search.

uhm.. the for ... in loop is where declare allNames? Not earlier, not later

The for in loop does all the work for you, it creates a variable and in each run of the loop it assigns the next property's in friends (so first run bill object and then in the next run steve object)


#3

Going back to basics.
key being a variable for the items in my object
Which automatically increment like a for(x=0;x<5;x++) kinda?

var list = function(friends) {
for (var key in friends) {
console.log(key);
};
list()


#4

yes, you seem to understand. in the other code you called your key allNames, the key can be named anything you like.

take a look at this code:

aList = ["one","two","three"]
for (i = 0; i < aList.length; i++){
   key = aList[i]
   console.log(key)
}

i think this is an okay representation of a for in loop, except it does all the steps for you. It will do the increment, and then after this increment assign the new value to key

Except then you have an object, instead of an array


#5

aaah yea Im starting to see I can do it either way, but this way has it done for me, thanks.

Im just trying to get my search to work now.


#6

now that you understand this, it shouldn't be too much trouble :wink:


#7

ooooh I cant say that. Im still struggling. I will show what I currently have that isnt working

var searchItem = "Steve"  //searching for steve
var search = function(friends) {  
    for(key in friends) { 
        if(friends[key].firstName === searchItem ) {
            //console.log(searchItem,"Found")
            console.log(friends[key]);
            return friends[key];
        } else {
            console.log(searchItem,"Not found")
        }
    }
};

search()

#8

Define a function search that takes a single argument, name

your function:

var search = function(friends)

doesn't look like your argument is name, it looks like friends instead.

then you should use use name in if statement (since that is the name you search for)

then you can pass searchItem into the function call:

search(searchItem);

#9

Yea went back and did the steps one by one and it made alot of sense.
Is name in function(name) a built in property? One expecting a string or?

var searchItem = prompt("Type a name, preferably Steve")
var search = function(name) {  
    for(key in friends) { 
        if(friends[key].firstName === name ) {
            console.log(searchItem,"Found")
            console.log(friends[key]);
            return friends[key];
        } else {
            console.log(searchItem,"Not found")
        }
    }
};
search(searchItem)

#10

there is one change i would personally make, which would be:

var searchItem = prompt("Type a name, preferably Steve")
var search = function(name) {  
    for(key in friends) { 
        if(friends[key].firstName === name ) {
            console.log(searchItem,"Found")
            console.log(friends[key]);
            return friends[key];
        }           
    }
    console.log(searchItem,"Not found")
};
search(searchItem)

why i made this change? With your code, if the name is not the first one, it will log that it didn't find anything, while the name might be later. with the above code, this only happens after the for loop is finished running (which means the name isn't actually there)


#12

oooh so it runs if statement in the for/in and if that paramater is never reached it will just proceed to the next line kinda thing?


#13

what? No? In each run of your loop, it evaluates if if is true, if it is it logs the found result and return is, causing the function to end. If if is false, the else clause will run, logging that nothing is found. which is weird to do this every run of the loop, i would personally only log not found after the loop is finished running

lets say the name we look for is the 6th one, with your code, it will first log not found 5 times, given the if condition is false 5 times. Kind of rubbish, don't you think?

With my code, it only logs not found after the loop is finished, which (IMHO) make more sense.


#14

Actually not sure now. ■■■■ it..

My results are
ghfdgfgsf Not found
ghfdgfgsf Found
ghfdgfgsf Not found
ghfdgfgsf Found
ghfdgfgsf Not found
ghfdgfgsf Found
ghfdgfgsf Not found

aaaah will sleep and try in the morning


#15

that doesn't make any sense. If you need more help post an updated version of your code (the full code please)


#16

Basically went back and redid the tutorial again, and got better results.

I dont really understand why this is happening like 5 times;
console.log(searchItem,"Found")
console.log(friends[key]);

var friends = {
    bill:{firstName: "Bill", lastName: "Cosby", number: "69-80085-69", address:["69 Pickadelly road" ,"Bullsville", "6969"]},
    steve:{firstName: "Steve", lastName: "Irwin", number: "90909-09090-90", address:["89 Dickadelly road" ,"Dullsville", "4969"]}  
};
//
//
//Add Random Number to Name
var randomNoName = prompt ("Add a random.number to Who?");
var test = function () {
    friends.randomNoName = Math.random();
    console.log(friends);
};
test(randomNoName);
//
//
var list = function(friends) {
    console.log("////////List all properties in Obj////////////////////////////")
    for (var key in friends) {  //kinda like for(x=0;x<5;x++) kinda, more automated
        console.log(key);
    }
}
list();
//
//
var searchItem = prompt("Type a first name, preferably Steve")
var search = function(name) {  
    console.log("////////Search for Name////////////////////////////")
    for(key in friends) { 
        if(friends[key].firstName === name ) {
            console.log(friends[key].firstName);
            return friends[key]; 
            //return stops function and returns a value, based on console.log
        };           
    };
    console.log(searchItem,"Not found") 
    //dont include else in for/in else it will iterate every time
};
search(searchItem)

#17

it seems to be the exercise, which most likely calls your search function, if you try it here it works fine

Oh, one more thing, if your list function:

var list = function(friends)

has a parameter, you should call it with an argument:

list(friends);

you can also leave the parameter and argument out, since the function has access to your friends object, the choice is yours, but you should do both or neither, not a mixture


#18

Time for me to return to my science studies.
Thanks for all the help! Shall return when my current assignment is done


#19

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