3

I was looking around and saw this page where they were using String and Array constructors while creating their variables.

How does this differ from not using them?

Example:

var str = "string"; // How I'd normally do it.
var str = new String("string"); // How they did it.

var arr = ["Array", "Item"]; // How I'd normally do it.
var arr = new Array("Array", "Item"); // How they did it.

How exactly do these two differ?

1
  • 1
    It is slower to create objects / arrays by new. Hopefully some guru can explain in depth. Commented Mar 3, 2014 at 1:49

1 Answer 1

3
var str = "string"; // typeof string

This is represented as block of memory, use it if you don't want to call a member on it

var str = new String("string"); // typeof object

This is a boxed object, which is slightly more resource consuming, but if you call i.e.

"Hello".length;

The JS parser must first create the boxed object from the string memory and then call the method, which is even slower.

The arrays syntax are always boxed objects in JS: [] is just syntax shorthand for new Array() AFAIK. Um, almost: see the zzzzBov's comment below.

Sign up to request clarification or add additional context in comments.

1 Comment

The only difference between new Array(...) and [...] is when you pass a single numeric argument. new Array(2) will create an array of length 2, while [2] will create an array with a value of 2 at index 0. Because of this surprising inconsistency it's recommended to always use the array literal syntax [].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.