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 trialRobert Farese
7,944 PointsI don't think I wrote this code in the most efficient way...
Here is how I answered this question...which came out correct but I can't imagine I wrote this in the most effective way. How can I consolidate all these if statements?
function arrayCounter (myArray) { if (typeof myArray === ‘string’){ return 0; } if (typeof myArray === ‘number’){ return 0; } if (typeof myArray === ‘undefined’){ return 0; } return myArray.length; }
2 Answers
Andrew Shook
31,709 PointsThey didn't teach it during the course, but the most effective way to do this is to use isArray.
function arrayCounter( myArray){
if( Array.isArray( myArray ) ){
return myArray.length;
}
return 0;
}
Jeff Busch
19,287 PointsHi Robert,
You can try this:
function arrayCounter (myArray) {
if(typeof myArray === 'string' || typeof myArray === 'number' || typeof myArray === 'undefined') {
return 0;
} else {
return myArray.length;
}
}
Robert Farese
7,944 PointsThanks Jeff! I had thought of using that operator...
Robert Farese
7,944 PointsRobert Farese
7,944 PointsHey Andrew! That's exactly what I was looking for. Thanks for your help!