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

Checking if a param is 'undefined'

Hi, so this function doeas NOT check if ar is 'undefined'. Any ideas why? The 'else if' part seems to check for that, but I still get a 'Bummer!'.

index.html
<!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>
      var arrayCounter = function(ar) {
        if (ar.isArray) {
          return ar.length;
        }
        if (typeof ar === 'undefined') {
          return 0;
        }
        else {
          return 0;
        }
      }

    </script>
  </body>
</html>

1 Answer

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

You need to change the syntax for .isArray.

It should be Array.isArray(ar) in your example. You can also remove the undefined clause.

So the full code you could use would be:

      var arrayCounter = function(ar) {
        if (Array.isArray(ar)) {
          return ar.length;
        } else {
          return 0;
        }
      }

Reference: Array.isArray()

Thx a lot! But how come this method Array.isArray(ar) is so long? Seems inconsistant with the rest of JS methods. Is it some kind of Angular/jQuery/dontKnowWhatElse trick or just a regular JS method?

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

Array.isArray() is an inherent method of the Array global object. Other methods, such as pop() and push() are instance methods which inherit from Array.prototype.

In essence, when using Array.isArray() you are accessing the global object of Array itself whereas the 2 other aforementioned methods are accessing methods of Array instances.

This is illustrated when creating an Array.

// Recommended Array instance creation
var myArray = [];
// What the above is doing is essentially the following
//    Which is another way to create an Array instance
var myArray = new Array();