I was reading in my Javascript book and it was talking about the difference between these two statements.
var s = "hello world"; // A primitive string value
var S = new String("hello world"); // A String object
I understand the difference but the book also mentioned (as like a little side note) that eval() will handle these differently but didn't mention how.
I tried looking around a google and couldn't find anything so I want to example.com and started messing around with it. I couldn't see a difference in the way that they are handled.
My question is: How does the eval() method treat these differently?
The main difference between String Literal and String Object is that String Literal is a String created using double quotes while String Object is a String created using the new() operator. String is a set of characters. Generally, it is necessary to perform String operations in most applications.
In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties. There are 7 primitive data types: string.
The eval( ) method of the Java JSObject class evaluates the JavaScript code contained in the string s in the context of the JavaScript object specified by the JSObject.
From the MDN:
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 as all other objects are, by returning the
object. For example:
s1 = "2 + 2"; // creates a string primitive s2 = new String("2 + 2"); // creates a String object console.log(eval(s1)); // returns the number 4 console.log(eval(s2)); // returns the string "2 + 2"
Consider this:
str = "alert('foo')";
obj = new String("alert('foo')");
eval(str); // produces an alert popup with 'foo' in it
eval(obj); // returns "alert('foo')" as a string
str = "arglebargle";
obj = new String('arglebargle');
eval(str); // reference error: arglebargle is not defined
eval(obj); // string: "arglebargle"
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