Literals and objects - When to use what?

I wonder when to use literals and when to use objects to create data type values.

Eg.

When I will use them:

/regexp/
"string"

and when they:

new RegExp("regexp")
new String("string")

Will they give me the same methods and properties?

+3
source share
2 answers

When you try to use one of these literals as an object, the literal is converted to an object (a wrapper is applied to it) inside, so you get access to any method or property that you are trying to use:

var a = /regexp/
a.test(aString);

... essentially the same as:

var a = new RegExp("regexp");
a.test(aString);

The only difference is that without the eval()only way to create Regex at run time is to use RegExp().

The same goes for the lines:

var b = "abc";
b.length;

... - , :

var b = new String("abc");
b.length;

typeof "ABC" typeof (new String("ABC")). "string", "". (. ).

. new String("ABC");" "ABC", "ABC". , "ABC": . Regexes , .

"ABC" ( , , ..)

+1

new RegExp() , , .

var x = "exp";
var regex = new RegExp("reg" + x);

, .

, , .

var arr = new Array( 3 ); // creates an Array with an initial length of 3

var arr = new Array( "3" ); // creates an Array with an initial length of
                            //    1 item that has the value "3"

, , .

+3

Source: https://habr.com/ru/post/1765723/


All Articles