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 trial

JavaScript JavaScript Foundations Functions Return Values

Stefan Alexandru
Stefan Alexandru
10,169 Points

Kinda stuck at the code challenge, what am i getting wrong ?

What am i getting wrong with this ?

function arrayCounter(){
        if(typeof arrayCounter === 'string', 'number', 'undefined'){
          return arrayCounter.length = 0;
       }else(arrayCounter.length);
        }

9 Answers

The simplest answer based only on what we've learnt up to this code challenge would be:

function arrayCounter (array) {
    if (typeof array === 'undefined')
                    return 0;
        if (typeof array === 'string')
                    return 0;
    if (typeof array === 'number')
                    return 0;
        return array.length
      }
Andrew Shook
Andrew Shook
31,709 Points

Simplest, but not the most compact or accurate. This would return the length of an object also, which means you could get false positives. Fact is, the most accurate and shortest way to answer this question was never taught in the JS course, and that would be to use isArray. After that the instanceof mentioned by Sean T. Unwin is probably the next best way since it won't return a false positive with Objects.

Aaron Graham
Aaron Graham
18,033 Points

Andrew Shook - I think properly qualified her statement with "based only on what we've learnt up to this code challenge". I do agree 100% with you though. The way I would do this is with Array.isArray() with a polyfill for older browsers.

Thank you Aaron Graham. I totally agree with you and Andrew Shook about the best way being Array.isArray(). However, for newbies, just getting started with JavaScript, all the answers offered above can be quite confusing. Like I said my answer was based only on what was taught in the JS course up to this challenge.

Sean T. Unwin
Sean T. Unwin
28,690 Points

I think this is the answer that was intended when the challenge was created. +1 for answering the question using concepts that were introduced up to this point in the course.

this was posted earlier in the thread as well by myself, though i'm glad this post received feedback on why it would return false positives!

Andrew Shook ,

It's fine to point out that this solution is not accurate but it is what can be reasonably accomplished at this point. It's pretty much a translation of the instructions.

To be fair, your own answer from a year ago that you're linking to here is also not accurate and will return the length of an object too., which is undefined.

Thanks so much for answering based on what we've learned so far in the module.

Sean T. Unwin
Sean T. Unwin
28,690 Points

This is a solution that works and will be backwards compatible with older versions of IE:

function arrayCounter(arr) {
  if(arr instanceof Array) {
    return arr.length;
  } else { return 0;}
}
Andrew Shook
Andrew Shook
31,709 Points

Yeah there a bunch of ways to answer this, but the problem is they don't teach them before this code challenge. I contacted treehouse about it code challenge. This is like the fifth or six time I've personally answered this question, and I've seen it asked on the forum at least a dozen times.

Sean T. Unwin
Sean T. Unwin
28,690 Points

I agree it could be considered a tricky question. I posted my above response to another thread where you and Jason Anello among others were discussing this question as well.

Andrew Shook
Andrew Shook
31,709 Points

Yeah that was last week or the week before. I think it comes up on the forum about twice a month.

Stefan Alexandru
Stefan Alexandru
10,169 Points

Thanks guys, manage to find solution on forum. Lots of things unexplained in this JavaScript course, and is affecting our learning flow.

Sean T. Unwin
Sean T. Unwin
28,690 Points

Lots of things unexplained in this JavaScript course, and is affecting our learning flow.

While the first part is true, I wouldn't necessarily attach the second part, at least as it relates to the first. There is a lot to learn about JavaScript and there are some intricate peculiarities within the language itself. So to put that in a negative fashion towards the course, I think, is being a little disingenuous. The course is designed to be a jumping off point into the JavaScript world. It takes a lot of time, experimentation and reading to know a lot about JavaScript. Also realize that in any programming language there is always more than one way to come to a solution.

Stefan Alexandru
Stefan Alexandru
10,169 Points

This code challenge proved to be a pain for so many, cause is all over the forum. Maybe you are viewing the this course from the perspective of a more advanced javascript user. I personally found challenges where the answer requires some things that they haven`t learned me or even remotely been referred/mentioned as to search outside the course or something. Overall treehouse courses for me , till now , have been really good , but i think when you want to teach other people a more complex program language you need to be very careful at the approach. Do the challenge based strictly on what you've tech , or refer to other sources or even mention the things you cant cover in the course so we , the newbies can get a grasp about them , and get a chance to resolve the challenges. If u make the user a load of frustration , he will be rising question on the course accuracy or himself not being able to learn something.

Sean T. Unwin
Sean T. Unwin
28,690 Points

Having thought about what you wrote above I have to say I actually agree with much of what you said and I understand your feelings about it. I sort of felt the same way on some of the challenges for the Python courses, but I appreciated that the challenges weren't spoon fed and motivated me to experiment and find answers.

I would like to add, however, that learning any programming language, library, or API is absolutely about searching for and reading resources and documentation. For JavaScript this is typically the relevant section on MDN.

Don't let this discourage you too much or in such a way that you wouldn't want to continue learning JavaScript. Everyone has questions and each person may learn in a different way.

Also, speaking for myself only, I see that my original answer was something more along the lines of an addendum than an answer to your question so I will try to think more in the perspective of the person asking the question as well as the context of that question. So thanks for that. :)

Stefan Alexandru
Stefan Alexandru
10,169 Points

I will not quit learning javascript , just that i have quit the javascript course on treehouse and attended to one on other site, it`s free and so much better . As for MDN i agree , very good documentation.

i just recently noticed "recommended other courses" blurbs. is that new? because that would be helpful here.

in other online courses (udacity specifically) they would encourage research to find an answer and even promote "how could you do this differently with more advanced learning/knowledge." which in general has been distinctly missing aside from some extra credits.

i think this is veering off into philosophy, in this specific case the solution is gotten to via things not covered in typical experience maps,and it is unique in this way from all else i've done at treehouse.

i'm not a beginner so it isn't as fatal to me as to the other posters, but it is a bit disorienting when it is also in such proximity to the scope coverage that is redundant to the previous chapter covering scope.

it also seems like a simple solution to this is requiring the previous knowledge/course in the track. i know that you don't want to inflate tracks with comprehensive knowledge of parallel or tangential concepts... but you already have jquery parallel to js basics...

That's nice, but nothing in this course taught simple conditionals... like how ELSE or how OR works.

You would have to have some other knowledge to see:

function arrayCounter (derp){
        if (typeof derp==='string'){
          return 0
        } else if (typeof derp==='number') {
          return 0;
        } else if (typeof derp==='undefined') {
          return 0;
        } else {
          return derp.length;
        };
      }

Or that it can be simplified to

function arrayCounter (derp){
        if ((typeof derp==='string') || (typeof derp==='number') || (typeof derp==='undefined')){
          return 0
        } else {
          return derp.length;
        };
      }

So the solution up above just giving the answer using instanceof is what is disingenuous, since the question is "what's wrong with my code," not "how would this be solved using anything in javascript, including that which wasn't covered yet in the course."

It isn't really a tricky question, there is simply nothing in this course specifically that has the knowledge on how to solve it. Taking from other courses --potentially in the tracks-- you should be able to know the syntax... but that's not necessarily true if going through the library.

So the less advanced solution requires knowing OR and ELSE (or at least just else) is equally absent as "how to check specifically for arrays/array objects."

Sean T. Unwin
Sean T. Unwin
28,690 Points

I understand what you're saying and I can see how my answer may seem obtuse.

If I may, I would like to suggest the Introduction to Programming JavaScript course which goes some of the concepts you mentioned. - I thought you were the op, Stefan, when I posted.

Would you think it would be satisfactory to have the Introduction to Programming JavaScript course show up as a suggestion to do first when looking at the JavaScript Foundations course?

Yep! It would be in there.

Of course every course couldn't contain everything about the topic within it, otherwise you'd have 1 course for each software!

But I do believe in this case it shouldn't be too difficult to replace the redundant videos / challenges on scope with one that teaches and/or if/then/else ...

http://teamtreehouse.com/library/javascript-foundations/variables/scope-2

is nearly identical to

http://teamtreehouse.com/library/javascript-foundations/functions/scope

Sean T. Unwin
Sean T. Unwin
28,690 Points

Scope can be confusing for many so I'm not sure those are so much redundant than letting the concept sink in.

While I do agree with you on some points, I feel the course is pretty good on it's own, provided you understand programming constructs and maybe some core JavaScript concepts (but I guess that's what this course is about :-) ).

This is why I suggested to do Introduction to Programming before taking JavaScript Foundations, and that it be should be noted before taking the latter.

Ultimately, the decision is not up to me, or you, it's up to the staff, although we can make suggestions to make things better for all students.

Shahab Ali
Shahab Ali
11,221 Points
function arrayCounter(array) {
        if (Array.isArray(array)) {
          return array.length

        }
        else { 
          return 0
        }

      }

I'm really a JS newbie but my solution worked at the first try. I'm really surprised reading more complex solutions here. Is anything wrong with mine?

 function arrayCounter(array) {
        if (typeof array === 'object') {
        return array.length;
        } else {
        return 0;  
        }}
Steven Walters
Steven Walters
10,573 Points

Juan,

That's what I came up with also.

--StevenKW

Hi Juan and Steven,

The problem with this solution is that a regular js object like {name : 'John'} will make the if condition true and the length of an object is undefined so your function will return undefined.

The currently accepted solution also suffers from similar problems but it's about the best you could come up with based on the course up to this point.

I recommend reading the mdn page on the typeof operator in order to see the limitations of it when used for a problem like this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

The Array.isArray() method is the best way that I know of to solve this problem properly.

Matthew Thompson
Matthew Thompson
4,500 Points

I am a complete beginner to programming and I managed to complete this question using just the information provided in the introduction to programming course and the material in this course. Granted it took me longer then any of the previous questions to complete but I guess that's how we learn. I love all of the different ways people approach this, my answer is a little longer than most of this (pretty similar to the first answer on here)

stephanie sutedja
stephanie sutedja
3,693 Points

Hi you guys, I wonder why this code doesn't this work:

function arrayCounter(array){ if (typeof array === 'string' || 'number' || 'undefined'){ return 0; } return array.length; }

It makes sense in my brain. If variable array is equal to 'string' or 'number' or 'undefined', then return zero. If it does not return the length. It doesn't work in the console, but my brain said it should work.

Thanks for your help.

Hi Stephanie,

It might help you to understand if you check this MDN Operator Precedence page.

There is a handy table there part way down the page which tells you the order that operators will be evaluated in.

typeof (15) has higher precedence than === (10) which in turn has higher precedence than || (5)

This means that the typeof and strict equality operators will be evaluated first before it gets to the logical OR's

This part typeof array === 'string' gets evaluated first and it will either be true or false depending on what gets passed in.

Then you either have:

false || 'number' || 'undefined'

or

true || 'number' || 'undefined'

The first one is true because the string 'number' is considered a truthy value. The second one is also true because the first operand is true

This means that your if condition is always true regardless of what gets passed in.

stephanie sutedja
stephanie sutedja
3,693 Points

Thanks for the info Jason :)