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 trialMicah Dunson
34,368 Pointshow do I find the length of "X" array passed in an array or 0 if a string, number, or undefined is passed?
The question is create a function "arrayCounter" that takes a parameter which is an array. The function must find the length of the array passed in or 0 if a string. number, or undefined value is passed in.
I don't know how to call out an array item without a name to define its length
I also don't understand how you would expect to get the length if the array contains a 'string', 'number', or 'undefined' value passed in it and you call for a return of 0. They can all be contained in an array
2 Answers
Chris Hubbard
2,253 Points@micah dunson
Haven't done this specific lesson so I hope I am leading you the right way here. Also, there are a couple different ways you could tackle this (provided I am properly understanding your question). Take a look at the comments in the function below.
function arrayCounter (param) {
// Use Array.isArray() method to make sure function param is an array
// Using typeof() operator will return "object" on an array in Javascript
var paramType = typeof(param);
var isArray = Array.isArray(param);
if ( isArray ) {
return param.length;
} else if (paramType === "string" || paramType === "number" || paramType === "undefined") {
return 0;
}
}
Andrew Shook
31,709 PointsThis question comes up a lot on the forum. You can find the answer you are looking for here. Best of luck.
Micah Dunson
34,368 PointsThanks a million. I knew I wasn't crazy about some things lol You've been a great help to my learning and sanity hahaha.
Micah Dunson
34,368 PointsMicah Dunson
34,368 PointsI have not covered this method of .isArray before. Thank you. This worked perfect and makes perfect sense.