Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating variable with constructor

Tags:

javascript

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?

like image 349
Spedwards Avatar asked Feb 28 '26 12:02

Spedwards


1 Answers

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.

like image 157
Jan Turoň Avatar answered Mar 03 '26 00:03

Jan Turoň



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!