Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Build an Interactive Website Form Validation and Manipulation Checking Values

how to return an array ?

Hi,

Got a bit stuck with the syntax this one... Do I need to create an array first? Do I need to put a function after .each and then .push the values into the array I've created previously? Can't I do it in one step?

function isValidEmail(argument) {
  if (argument.indexOf("@") != -1){
    return true;
  }
  else 
    return false;
}

function requiredValues() {
  return $(".required").each().val()
}

2 Answers

Hi Melinda,

The .each() method takes a function as it's argument. So you need to pass a function in. In this case, an anonymous function.

The method will then iterate over each of the matched elements and that function will be called so you can perform some action on each one. In this case, you want to get the value of the required field and push it onto an array so you can later return that array when you've finished iterating over all the matched elements.

So yes, you would need to create an array first to hold these values. Then push each of the values onto the array. And finally return the array.

Post back here if you get stuck on the implementation details.

Also, you can shorten your first function to this:

function isValidEmail(email) {
  return email.indexOf('@') !== -1;
}

You'll see this pattern come up a lot. Where you are basically saying, "if this expression is true, then return true, else the expression was false and you should return false" .

Since the expression email.indexOf('@') !== -1 is going to evaluate to true or false you can simply return the value of that expression. You don't have to explicitly return true or false.

Let me know if that doesn't make sense and I'll try to explain it differently. Or maybe someone else can explain it better.

Kevin Lozandier
PLUS
Kevin Lozandier
Courses Plus Student 53,747 Points

Hi, Melinda Biber:

If you want me to return an entire array (to manipulate later) You merely pass in the name of the array.

It's a different situation if you want to visually output the values of an array to the DOM. Is that what you what you meant instead?