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 trialOliver Bannister
5,143 PointsChallenge 1 of Return Values
"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".
Can anyone shed any light onto this challenge? I am totally stuck.
2 Answers
Adrian Melendez
5,555 PointsThe challenge is a little strange because 'typeof' is discussed in the video but that isn't the best way to determine what is or isn't an array.
The code I wrote which worked is:
function arrayCounter(ArrayParam) {
if ((typeof ArrayParam === 'string') ||
(typeof ArrayParam === 'number') ||
(typeof ArrayParam === 'undefined')){
return 0;
} else {
return ArrayParam.length;
}
};
As you can see, it works even though there are non-array objects that the function will still try to return a length for.
Better code posted by Dave McFarland uses 'instanceof Array' to determine what is or isn't an array but 'instanceof' isn't mentioned anywhere in the video:
function arrayCounter (array) {
if (array instanceof Array) {
return array.length;
} else {
return 0;
}
}
var myArray = [1,2,3];
console.log(arrayCounter(myArray)); // prints 3 to the console
var myString = 'test';
console.log(arrayCounter(myString)); // prints 0 to the console
var myObj = { name: 'object' };
console.log(arrayCounter(myObj)); // prints 0 to the console
Oliver Bannister
5,143 PointsThank you for your answer! Much appreciated.