Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does typeof String return function

Tags:

javascript

Why does:

console.log( typeof String ); return function when it's an object?

like image 346
Robert Rocha Avatar asked Mar 11 '15 00:03

Robert Rocha


2 Answers

String is the constructor of the string object. All constructors are functions, therefore the return value you are seeing.

You can see this yourself by creating code like this:

var MyObject = function (value) {
    this.value = value;
};

MyObject.prototype.getValue = function () {
    return this.value;
}

console.log(typeof(MyObject)); // function
console.log(typeof(new MyObject(1))); // object
like image 102
unobf Avatar answered Sep 20 '22 02:09

unobf


This is because there is a big difference between String and "String". Let me elaborate:

console.log(typeof String)

will return function while

console.log(typeof "String")

will return string.

This is because String is actually a global constructor. It is used to create strings!

var string = new String('2 + 2'); // creates a String object
console.log(string);        // returns the string object. try it

The "String" is a string as javascript converts it into a string primitive.

var string1 = '2 + 2'; // creates a String object
console.log(string1);        // returns the string primitive. try it
like image 29
Ally Jr Avatar answered Sep 19 '22 02:09

Ally Jr