Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialNazaam Kutisha
7,667 Pointshelp me with this challenge.
Around line 17, create a function named 'arrayCounter' that takes in a parameter which is an array. The function must return the length of an array passed in or 0 if a 'string', 'number' or 'undefined' value is passed in.
I was thrown by the task of embedding an array into a function, and passing values of 'string' or 'number'
( "The function named 'arrayCounter' that takes in a parameter which is an array") ??? Im not sure of what he means here.
My best shot at this was.
<h1>JavaScript Foundations</h1>
<h2>Functions: Return Values</h2>
<script>
function arrayCounter (string, number) {
if (typeof number === 'undefined'){
number = '0';
}
//console.log(greeting + "world! " + name);
return string.length;
}
</script>
Many Thanks, Nazaam
2 Answers
Dino Paškvan
Courses Plus Student 44,108 PointsYour function should accept only one parameter — an array. Of course, in JavaScript, you can't dictate what type a function accepts, so you check what it is, and depending on the result of that check, you do different things. In this case, you check if it really is an array. If it is, you return the length of the array. If it's not, you return 0
.
function arrayCounter(array) { // take one parameter, let's call it array
if (typeof array === "string" || typeof array === "number" || typeof array === "undefined") { // check if it's a string or a number or undefined
return 0; // if it is, return 0, and the function stops executing here
} // if it's not, the code inside the if won't execute
return array.length; // return the length of the array
}
alex mattingley
7,508 PointsCheck out this past forum: