Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item. Then I can loop over it without fear of an error.

So how do I check if the variable is an array?


I've rounded up the various solutions below and created a jsperf test.

share|improve this question
5  
I thought you meant to 'check if object is an array', but you want to check if 'object is an array of strings or a single string' specifically. Not sure if you see it? Or is it just me? I was thinking of something more like this... am I the one missing something here? – rr1g0 Jul 23 '15 at 18:23
41  
TL;DR - arr.constructor === Array is fastest. – Neta Nov 23 '15 at 22:37
    
You had an important part of the screenshot cut, above the test, where it's written where did the test occur. My test is very different. – vsync Dec 22 '15 at 15:51
1  
@vsync There's a hyperlink. You guys can run it as much as you like. The screenshot is there just for people that are too lazy to click. – mpen Dec 22 '15 at 18:38
1  
jsben.ch/#/QgYAV - a benchmark for the most common ways – EscapeNetscape Oct 24 at 17:34

31 Answers 31

 var length = 16;                               // Number
 var lastName = "Johnson";                      // String
 var cars = ["Saab", "Volvo", "BMW"];           // Array
 var x = {firstName:"John", lastName:"Doe"};

 Object.prototype.myCheck= function(){
 if (this.constructor === Array){
          alert('array');
        }else if (this.constructor === Object)
       {
         alert('object');
        }else if (this.constructor === Number)
        {
          alert('number');
        }else if (this.constructor === String)
        {
          alert('string');
        }

 }
 cars.myCheck();
 lastName.myCheck();
 length.myCheck();
share|improve this answer
1  
Why did you make your method a prototype of Object if you aren't going to call it like cars.myCheck()? – mpen Jul 8 '15 at 16:37
    
yes mark you are correct it should be cars.myCheck().. updated the answer – Gaurav Jul 9 '15 at 17:25
2  
Still no. If you're making it a prototype method, you should drop the obj argument and use this inside instead. Also, a function that just alerts isn't of much use to anyone. – mpen Jul 9 '15 at 20:17
    
Oops sorry updated the same – Gaurav Jul 14 '15 at 10:15

protected by durron597 Sep 23 '15 at 18:27

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.