In JavaScript, from my understanding, the below are all same:
var carter2 = new String();
var carter2 = '';
var carter2 = "";
Which one is the most preferred?
In JavaScript, we can initialize a String in the following two ways: Using String literal. Using "new" Keyword.
String initialization is one of the basic parts of programming. String initialization means assigning a value to the variable before it's used in the java program. String initialization can be done in two ways: Object Initialization. Direct Initialization.
Don't use
var str = new String();
Because
var str = new String("dog");
var str2 = new String("dog");
str == str2; // false
But
var str = "dog";
var str2 = "dog";
str == str2; // true
However, because of type coercion, the following works (Thanks to Rocket for pointing it out)
var str = new String("dog");
var str2 = "dog";
str == str2; // true
Single and double quotes don't matter, except for what quotes need to be escaped. Many others have noted that single quotes are better when creating HTML strings, since XHTML expects attributes to have double quotes, and you won't need to escape them.
When doing new String()
, you are not being returned a string
primitive, but a String
object.
For all intents and purposes it acts like a string
primitive, but there are cases where it won't. For example:
var a = new String('body');
jQuery(a); // This will *not* function as expected
// This will make a jQuery object containing a "String" object
// It will NOT treat it as a selector string
Also when comparing things, there may be problem. When you compare objects in JavaScript, it's only true
if they are the same exact object, not just the same value. Example:
var a = new String('test');
var b = new String('test');
var c = a;
var d = 'test';
a === b; // false, a and b are different objects (a == b is also false)
c === a; // true, a is the same object as c
c === b; // false, c (which is a) is a different object than b
d === a; // false, d is a primitive and a is an object, they are not equal
'test' === d; // true, they are both string primitives
d == a; // true, this uses "==" so only value is compared, not type
You can use .valueOf()
to convert a String
object to a string
primitive.
new String('test').valueOf() === 'test'; // true
So, I highly suggest using var a = ''
or var a = ""
. As for single quotes vs. double quotes, there is no difference. Consider this example:
var a = "My name is Joe O'Ryan";
var b = 'My name is Joe O\'Ryan'; // need to escape the '
var c = 'Joe said: "Hi"';
var d = "Joe said \"HI\""; // need to escape the "
So, it's up to you whether to use '
or "
, but I suggest those over new String()
.
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