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 trialTong Vang
9,926 PointsCreate a function to return the length of an array or 0 if a length is not present('undefined', 'string', or 'number'.
I'm lost. This is what I tried:
function arrayCounter () { if (.length = "undefined) { return 0;} else { return .length; } }
Help....
5 Answers
Denny Ku
Courses Plus Student 7,437 PointsDid you try to add the parameter to fix it? (Or you can try copy and paste my code to it,because it works just fine :) Then the problem may cause by typo. ) Back to question,if you use the ".length" to test undefined, it will return numeric 9. Besides, if I take other string to your function, it would return numeric value, won't equal to "undefined". EX: "hello".length = 5 "hello" is a string , not array , but its length != "undefined" .
Tong Vang
9,926 PointsBoth method worked. I must of mistyped on Denny's suggestion. I think they wanted Nick's method. Testing for "object" is ingenuious.
Thanks to you of both. I didn't even know I could use 'array', 'number', 'string'. I thought number & string were strings themselves. And array need to be defined first. These videos are very lite. The challenge are making up for it though. Without the forum, I would probably quit.
Thanks again guys.
Denny Ku
Courses Plus Student 7,437 PointsFirst of all , you forget your parameter Then you can use the cosole to check out the type of array, you will find it's an object. And in jacascript, the other option during this challenge aren't object, so you can try this :
function arrayCounter(array) {
if(typeof(array) == "object"){
return array.length;
}
else
return 0;
}
Tong Vang
9,926 PointsI've tried what you suggested and it returned : arrayCounter() is missing. I know. The function is there but it is ignoring it. I don't know what else to do.
Nick Calabro
16,335 PointsYou want the function to make sure its none of the three types listed first. So, you'll have in your if statement if(typeof(array)=="undefined" || typeof(array)=="string" || typeof(array)=="number"){ return 0;} else {return array.length;}
I got stuck on this one too. Im pretty sure this is how i solved it, let me know if it works out. BTW: the '||' means or, so we're making sure its not "this" OR "that" OR "theotherthing" I hope I'm making sense :)