Are strings objects?

Speaking about language types, Strings are values of the String type.

The language has five primitive types, which are String, Number, Boolean, Null and Undefined.

There are String objects (also for Number or Boolean), they are called primitive wrappers, they are created when you use the constructor function associated with them, for example:

typeof new String('foo'); // "object"
typeof 'foo';             // "string"

But don't get confused with them, you will rarely need to use primitive wrappers, because even if primitive values are not objects, you can still access their inherited properties, for example, on a string, you can access all members of String.prototype, e.g.:

'foo'.indexOf('o'); // 2

That's because the property accessor (the dot in this case) temporarily converts the primitive value to an object, for being able to resolve the indexOf property up in the prototype chain.

About the constructor function you have in your question, as you know, it won't return the string.

Functions called with the new operator return an implicit value, which is a new object that inherits from that function's prototype, for example:

function Test () {
  // don't return anything (equivalent to returning undefined)
}

new Test() instanceof Test; // true, an object

If an object is returned from the constructor, that newly created object (this within the constructor) will be lost, so the explicit returned object will come out the function:

function Test2() {
  return {foo: 'bar'};
}

new Test2().foo; // 'bar'

But in the case of primitive values, they are just ignored, and the new object from the constructor is implicitly returned (for more details check the [[Construct]] internal operation, (see step 9 and 10)).


In JavaScript, strings come in two flavors:

  1. There is a String language type which contains values like "foo" and 'bar'. Those values are primitive values. Read about the String type here

  2. Then there is a String constructor. (A constructor is a function object which is used to create new instances of a certain "class" (or pseudo-class)). So this: new String("foo") will create a new object (a value of the type Object), which contains the primitive value "foo". Read about the String constructor here

In practice you don't use the new String('foo') notation, but the string literal notation 'foo'.


So to answer your question:

In JavaScript, strings are not objects. They are primitive values. However, there exist String objects which can be used to store string values, but those String objects are not used in practice.

Tags:

Javascript