Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Literals and Objects - When to use what?

Tags:

javascript

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

Eg.

When do I use these:

/regexp/
"string"

and when these:

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

Will these give me the same methods and properties?

like image 762
never_had_a_name Avatar asked Dec 16 '25 19:12

never_had_a_name


1 Answers

new RegExp() can be useful when you want to concatenate a value stored in a variable.

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

I don't know of any reason not to use String literals, though.

An example of where you may get an unexpected result using a constructor is when creating an Array.

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"

Overall, I think you'd be safe sticking to literals.

like image 51
user113716 Avatar answered Dec 19 '25 09:12

user113716



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!