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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With