new
operators with the String
, Number
and Boolean
Objects JS-0080 9329 (e.Query = function (e) {
9330 (this.clauses = []), (this.allFields = e)
9331 }),
9332 (e.Query.wildcard = new String('*')), 9333 (e.Query.wildcard.NONE = 0),
9334 (e.Query.wildcard.LEADING = 1),
9335 (e.Query.wildcard.TRAILING = 2),
There are three primitive types in JavaScript that have wrapper objects: string
, number
, and boolean
. These are represented by the constructors String
, Number
, and Boolean
respectively. The primitive wrapper types are used whenever one of these primitive values is read, providing them with object-like capabilities such as methods.
It's also possible to manually create a new wrapper instance:
const stringObject = new String("Hello world");
const numberObject = new Number(33);
const booleanObject = new Boolean(false);
Although possible, there aren't any good reasons to use these primitive wrappers as constructors. They tend to confuse other developers more than anything else because they seem like they should act as primitives, but they do not.
const stringObject = new String("Hello world");
console.log(typeof stringObject); // "object"
const text = "Hello world";
console.log(typeof text); // "string"
const booleanObject = new Boolean(false);
if (booleanObject) { // all objects are truthy!
console.log("This executes");
}
The first problem is that primitive wrapper objects are, in fact, objects
. That means typeof
will return "object" instead of "string", "number", or "boolean".
The second problem comes with boolean
objects. Every object is truthy, which means an instance of Boolean
always resolves to true even when its actual value is false
. For these reasons, it's considered a best practice to avoid using primitive wrapper types with new
.
const stringObject = new String("Hello world");
const numberObject = new Number(33);
const booleanObject = new Boolean(false);
const stringObject = new String;
const numberObject = new Number;
const booleanObject = new Boolean;
const text = String(someValue);
const num = Number(someValue);
const object = new MyString();