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 trialJason Nelson
9,127 Pointsproblems with function if statements
I'm having a issue with function challenge state 5. It's asking to return the Array length if passed in parameter is an array. Otherwise, if it's a string, undefined, or number to return 0. I get one of two errors, either it says I'm missing the function arrayCounter or it says gets 0 when the array 1,2,3 is passed in.
Here are some solutions I have tried
function arrayCounter (x) { if (x === 'array') { return array.length; } if (x === 'string', 'undefined', 'number') { return 0; } };
function arrayCounter (array) { if (typeOf x === 'array') { return array.length; } if (typeOf x === 'number', 'string', 'undefined') { return 0; } };
2 Answers
Curtis Schrum
10,174 PointsYeah I love the course I do but honestly TypeOf is terrible for finding out if something is an array. Without seeing all the code I can give you an idea of how to find out of its an array. Using variable X
if (x.isArray){
//Do stuff here
}else if (typeof x === 'number'){
//do stuff here if number
}else if(typeof x === 'string'){
//do stuff here if string
}else{
//final catch all
}
See if that helps
Jason Nelson
9,127 PointsI tried this and still no luck..
<!DOCTYPE html> <html lang="en"> <head> <title>JavaScript Foundations: Functions</title> <style> html { background: #FAFAFA; font-family: sans-serif; } </style> </head> <body> <h1>JavaScript Foundations</h1> <h2>Functions: Return Values</h2> <script>
function arrayCounter(x) {
if (x.isArray) {
return x.length;
}else if
(typeof x === 'string' || 'number' || 'undefined') {
return 0;
}
}
</script>
</body> </html>
Curtis Schrum
10,174 PointsYeah your right for whatever reason isArray is not working. So I went in and solved it, I had to use instanceof which I personally consider a back practice I also had to break up the if statement into multiple lines putting them all in the way I wanted which was using != was not working either. Below is the solution
function arrayCounter(x){
if(typeof x == 'undefined'){
return 0;
}else if (typeof x == 'string'){
return 0;
}else if (typeof x == 'number'){
return 0;
}else if (x instanceof Array){
return x.length;
}
}
Jason Nelson
9,127 PointsJason Nelson
9,127 PointsAwesome! Got it to work with your solution.