FAQ: Code Challenges: Intermediate JavaScript - greetAliens()

This community-built FAQ covers the “greetAliens()” exercise from the lesson “Code Challenges: Intermediate JavaScript”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

FAQs on the exercise greetAliens()

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Hi,
I somehow got it working, but is not passing, why the code below isn’t right even so it gives the right answer? Thx

const aliens = ["Blorgous", "Glamyx", "Wegord", "SpaceKing"];

function greetAliens(){
for (let i = 0; i < aliens.length; i++){
  console.log('Oh powerful '+ aliens[i] +', we humans offer our unconditional surrender!');
}
};

greetAliens(aliens);

// Oh powerful Blorgous, we humans offer our unconditional surrender! 
// Oh powerful Glamyx, we humans offer our unconditional surrender! 
// Oh powerful Wegord, we humans offer our unconditional surrender! 
// Oh powerful SpaceKing, we humans offer our unconditional surrender! 

It may not have come up, but now is a good time to present a different form of for loop…

for x of object

The of operator refers to membership. x in this loop is a value, not an index.

for (let x of aliens) {

}

It’s possible the SCT is expecting a template literal, that is an ES6 string that permits variable interpolation.

`Oh powerful ${x}, we humans offer our unconditional surrender!`
2 Likes

Thank you for your reply! Got it.
Anyway, I am moving slow and even so I understand well several topics, without immidiate practice it is becoming a little confusing.
Appreciated.

1 Like

Howdy partners,

I have a few things I don’t understand about the functional code below:

  1. the arr is a variable that represents 1 item in the array, but I don’t see how the code understands that arr refers to the aliens array. It is linked nowhere. In my logic ‘arr’ would need to be replaced by ‘aliens’ everywhere for this to function but this is not necessary.

  2. how is it irrelevant if the array lives above or below the for loop function? If you place the array after the for loop you’d think that it would get stuck for not having the array ‘available’.

const greetAliens = arr => {
      for (let i = 0; i < arr.length; i++) {
            console.log('Oh powerful ' + arr[i] + ', we humans offer our unconditional surrender!');
      }
}

const aliens = ["Blorgous", "Glamyx", "Wegord", "SpaceKing"];

greetAliens(aliens)

In fact that is what it is replaced with in this instance. The parameter (arr) is the local name given to the argument in function call…

greetAliens(aliens)

The function iterates over all the items in the array, as it were. It also accepts any array by any name. That’s what makes the function re-usable.

3 Likes

I am struggling to understand the definations of for statements and how the conditions work in this example;

Can the 3 expressions of the for statement be explained in context of the below example?

const greetAliens = aliens => {
for (let i = 0; i < aliens.length; i++) {
console.log('Oh powerful ’ + aliens[i] + ‘, we humans offer our unconditional surrender!’);

}
}

Thanks

I used two different methods to get the output the lesson requested, but neither one got a check box. m I’ll be honest it drove me nuts for a good 30 mins. I ended up just clicking the get solution (which made me mad lol). Why didn’t either of my functions pass?

function greetAliens(arr){
    for (let i = 0; i < aliens.length; i++) { // for loop conditions
      console.log(`Oh powerful ${aliens[i]}, we humans offer our unconditional surrender!`)
    };
  }

// alternative solution using for...of

/*
const greetAliens = (arr) => {
    for (const x of aliens){
        console.log(`Oh powerful ${x}, we humans offer our unconditional surrender!`)
        
    };
}
*/


const aliens = ["Blorgous", "Glamyx", "Wegord", "SpaceKing"];

greetAliens(aliens)

for code samples goes, if i attempt to introduce more aliens:

const aliens = ["Blorgous", "Glamyx", "Wegord", "SpaceKing"];

const moreAliens = ['Cybermen', 'Daleks', 'Slitheen'];

greetAliens(aliens);
greetAliens(moreAliens);

things do not go as planned. I expected to see my doctor who inspired aliens (cybermen, daleks and so forth). That is not happening. That should work. See if you can figure this out, otherwise I will help you further.

for the first code sample, you attempt to use function declaration, here is some documentation to help you:

https://developer.mozilla.org/nl/docs/Web/JavaScript/Guide/Functions#Function_declarations

if i compare an example from the mdn documentation:

function square(number) {

with your function deceleration:

function greetAliens(arr) = {

I see a mistake, do you see it as well?

Second code sample, there is a small typo in offer

If you need more help, please post an updated version of your code. Thank you :slight_smile:

1 Like

I updated the code, my mistake with the ‘=’ in the first function, as I copy/pasted from my vscode copy of my code and I didn’t notice the error, this was detected in the codecademy editor.

the other points (that your function does not work for multiple lists) and the small typo in offer (second code sample) still stand

function greetAliens(arr){
    for (let i = 0; i < arr.length; i++) { // for loop conditions
      console.log(`Oh powerful ${arr[i]}, we humans offer our unconditional surrender!`)
    };
  }

// alternative solution using for...of

/*
const greetAliens = (arr) => {
    for (const x of arr){
        console.log(`Oh powerful ${x}, we humans offer our unconditional surrender!`)
        
    };
}
*/


const aliens = ["Blorgous", "Glamyx", "Wegord", "SpaceKing"];
const moreAliens = ['Cybermen', 'Daleks', 'Slitheen'];


greetAliens(aliens)
greetAliens(moreAliens)

Seems to work fine now? :slight_smile: You corrected the mistakes

I tried this a couple of ways in Visual Studio Code. greetAliens() works fine in both Codecademy and VSC. With greetAlien() only the first element from the array gets logged to the console.

Why is that? Does return halt a for loop?

seems you answered your own question? Its the only difference between the codes, so surely that is the answer

return hands back data to the caller, meaning its done executing. Sort of like when you hand in an assignment without filling in all the questions :wink:

1 Like

When you can’t use forEach, you use for(...of...).
Is it cheating?

 greetAliens = array => {
  for(string of array) {
    console.log(`Oh powerful ${string}, we humans offer our unconditional surrender!`)
  }
}

No. It is just old school, sort of. for..of is new, but implementation of the for loop is not.

When we just want to do something with each element in an array, Array.forEach() is rather sweet since we can write multiple utility functions for various purposes and use them as the callback.

greeting = alien => {
  console.log(`Oh powerful ${alien}, 
    we humans offer our unconditional surrender!`)
}
farewell = alien => {
  console.log(`Farewell ${alien}, 
    we humans are glad to see you go!`)
}

aliens.forEach(greeting);

aliens.forEach(farewell);

Here you go, @ruby2561167188. Hope this explains it a bit.

for

(let i = 0; //This part creates a variable called 'i' and sets it equal to 0

i < aliens.length; //This part in full would be 'if the statement 'i' < (is less than) aliens.length returns true do the next part.

i++; //This part increases i by 1 each time it is run.

The first run through i = 0.
Second run through i = 1.
Third i = 2.
Fourth i = 3.

As there are four objects in the array, the for statement stops. It will attempt a fifth run through but that would mean that i = 4 which is no longer less than aliens.length.

Another way of thinking about it, which might help visualise is:

const greetAliens = (alien) => { 
  let i = 0;
  while (i < alien.length) {
    console.log(`Oh powerful ${alien[i]}, we humans offer our unconditional surrender!`);
    i = i + 1;
  }
};

Hope this helps @ruby2561167188. :slight_smile:

2 Likes

So I’ve got this code:

const greetAliens = arr => {
  for (let i = 0; i < arr.length; i++) {
    console.log(`Oh powerful ${aliens[i]}, we humans offer our unconditional surrender!`)
  }
}

const aliens = ["Blorgous", "Glamyx", "Wegord", "SpaceKing"];

greetAliens(aliens);

It does print to the console exactly what I wanted but exercise is not passed. Any Idea why?

If we introduce more aliens:

const aliens = ["Blorgous", "Glamyx", "Wegord", "SpaceKing"];
const moreAliens = ['a', 'b', 'c'];

greetAliens(aliens);
greetAliens(moreAliens);

you can give these aliens cooler names if you like, but point still stands. Trying to introduce more aliens should work, but it currently doesn’t.

1 Like