Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell difference between object and string in javascript?

I have a javscript function (actually a jQuery plugin) which I will want to call as either

myFunction("some input");

or

myFunction({ "prop": "value 1", "prop2": "value2" });

How do I, in the function, tell the two apart?

In other words, what should go in the if conditions below?

if (/* the input is a string */)
{
    // Handle string case (first of above)
}
else if (/* the input is an object */)
{
    // Handle object case (second of above)
}
else
{
    // Handle invalid input format
}

I have jQuery at my disposal.

Update: As noted in an answer, if the input is new String('some string'), typeof(input) will return 'object'. How do I test for new String(''), so I can handle that the same way as ''?

like image 297
Tomas Aschan Avatar asked Aug 12 '11 11:08

Tomas Aschan


People also ask

How do you know if its a string or an object?

Use the typeof operator to check if a variable is a string, e.g. if (typeof variable === 'string') . If the typeof operator returns "string" , then the variable is a string.

Is string considered as object in JavaScript?

However, JavaScript strings are considered a primitive datatype, which means they are not objects. This fact is crucial because primitive datatypes do not have methods or properties.

Are object and string the same?

Strings are objects in Python which means that there is a set of built-in functions that you can use to manipulate strings. You use dot-notation to invoke the functions on a string object such as sentence.


1 Answers

if( typeof input === 'string' ) {
    // input is a string
}
else if( typeof input === 'object' ) {
    // input is an object
}
else {
    // input is something else
}

Note that typeof considers also arrays and null to be objects:

typeof null === 'object'
typeof [ 1, 2 ] === 'object'

If the distinction is important (you want only "actual" objects):

if( typeof input === 'string' ) {
    // input is a string
}
else if( input && typeof input === 'object' && !( input instanceof Array ) ) {
    // input is an object
}
else {
    // input is something else
}
like image 135
JJJ Avatar answered Sep 27 '22 20:09

JJJ