Play Home Contribute Github Join Us! Discourse Staff Members Github Contribution Guides Team

Trojan Yeti - How does the function work?


I already beat this level (Trojan Yeti - Cloudrip Mountain), but I was wondering how this level works.
In this level, you are supposed to find the “wereyetis”, which are peasants, and then send them into the enemy camp.

How does the program (specifically the function findFriendByName(name)) find the wereyeti? I don’t understand the function.

Here is the code (only the function, which was already given):

// You need to defeat ogres.
// Send wereyeti peasants to the ogre camp and watch.

// This function returns a friendly unit by the name.
function findFriendByName(name) {
    var friends = hero.findFriends();
    for (var i = 0; i < friends.length; i++) {
        if (friends[i].id == name) {
            return friends[i];
    return null;

Thank you in advance! :heart:

This is how it works:

  1. Firstly you call the function: findFriendByName(name). The name variable will be something like: “bob”. A string (because it has quotes around it.)
  2. Now the algorithm loops through the friends array. It starts on friends[0] and moves all the way to the last friend.
  3. Next it takes the .id of the current friend, which will also be a string: e.g. “larry”. Then it checks if it’s the same as the name you inputted into the function, which was “bob”.
  4. Does “larry” == “bob”? No is the answer, but if the was “bob” it would return the friend. Not the name, but the friend itself. That’s called an object. When it returns the friend the function stops.
  5. If none of the friends names match the name variable the function returns null. == nothing.

I hope this helps,

1 Like

Ohh, thank you!!
I was confused why we needed to find the friend when we already had the list of wereNames. The wereNames list only has the string names, but we can’t command a string, we need the object.
This makes much more sense now, thank you! :heart:

1 Like