HappyCoding HappyCoding - 4 months ago 11
Javascript Question

Difference between typeof(/\s/) and $.type(/\s/)

I don't understand why it's throwing message

object
when I try:



alert(typeof(/\s/))





To check again, I've made a change:



alert($.type(/\s/))

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>





We've got
regexp
now.

So, my question: why is
typeof(/\s/)
an
object
instead of
string
or
regexp
in javascript?

Answer

A regular expression is an "object" because it’s an object, just like Date, etc. A regular expression is an object that describes a pattern of characters.

If you use typeof with an object, you get "object"

Some other examples:

typeof []; // "object"
typeof null; // "object"
typeof /regex/ // "object"
typeof new String(""); // "object"

With $.type

If the argument is either a primitive value or an instance of a standard built-in ECMAScript object, the [[Class]] internal property is used to determine the type.

Example:

jQuery.type( /test/ ) === "regexp"

Documentation on $.type