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

|| or boolean in if statements

In the challenge, I am trying to condense my if statements into 1, instead of using multiple else if's that do the same thing.

This doesn't work...why?

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

But this works, but it seems redundant with all the else if's that do practically the same thing.

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

1 Answer

Here is a simplified version to show how to use the || (or operator)

    function arrayCounter(a) { 
        if (typeof a === "number" || typeof a === "undefined" ) { 
            console.log(0);
        } else { 
            console.log(a.length); 
        } 
    }

       arrayCounter(25);
       arrayCounter("adam");

So to be clear you need to use the typeof each time. Just copy this into an html page and fire it up in a browser and view the console output for each time the function is called

Ah, I see. I didn't realize that typeof had to be repeated. Thank you!

Your welcome!