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 trialMichael Baker
7,731 Pointshow do you pass an array as a parameter in a function?
Here's as far as I got:
function arrayCounter (array) {
if (typeof array === 'undefined', 'string', 'number'){
return 0;
}
return array.length;
}
what am I doing wrong here...?
4 Answers
Dave McFarland
Treehouse TeacherYour conditional statement isn't correct. You can't use commas like that. You'd need to create three tests using the || operator like this:
if (typeof array === "undefined" || typeof array === "string" || typeof array === "number" )
However, even that won't correctly test for an Array. You're better off using JavaScript's instanceof
operator. It can tell you if a variable is an array or not like this:
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
Michael Baker
7,731 PointsThanks Dave, That was a tricky one - I assumed I was being asked how to test for those 3 instances (string, undefined or number). Making a catch-all is much cleaner. Michael
Michael Baker
7,731 PointsThanks Dave, That was a tricky one - I assumed I was being asked how to test for those 3 instances (string, undefined or number). Making a catch-all is much cleaner. Michael
Dave McFarland
Treehouse TeacherMichael,
I think my solution works better than testing for 'string', 'undefined' and 'number', because in JavaScript there are other types as well, such as boolean, function and object. What's even trickier is that if you use typeof
with an array you don't get 'array' as the result; you get 'object'.
console.log(typeof [1,2,3]); // prints 'object' NOT 'array'
However, since this is part of a code challenge, my answer may not work. I think the code challenge is looking for the use of the typeof operator like this:
var arrayCounter = function(array) {
if (typeof array === 'string' || typeof array === 'number' || typeof array === 'undefined') {
return 0;
} else {
return array.length;
}
}