
Learn about, in what way the string primitive and string objects are different in javascript.
We can create string in three ways,
1. var a = "first way"; // we can also use single quotes
2. var b = String("second way");
3. var c = new String("third way");
// also we can create using
4. var d = a + '';
The 1 and 2 will create primitive string , where as 3 will create a String object. But we can call all the string methods on the primitive string created from 1 and 2 , when we call one of the String object method on primitive String the browser will automatically convert the primitive string into string object .
Check the type of the strings created using typeof operator
typeof a // "string"
typeof b // "string"
typeof c // "object"
The string primitive is always parsed, i.e(string literal are treated as source code) , where as the string object is evaluated into a single string .
String primitives and String objects also give different results when using eval().
Primitives passed to eval are treated as source code.
String objects are treated like other objects , and it returns the object.
var a = "12 + 12";
eval(a); // 24
var b = new String("12 + 12");
eval(a); "12 + 12"
So how we can use String object in eval ?
We can use valueOf() method in String object which will return the string as primitive value
var a = new String("12 + 12");
eval ( a.valueOf() ) // 24
This above concept works same for Numbers and Boolean.