Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does eval() treat a string object differently from a primitive string value?

Tags:

javascript

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?

like image 288
Benjamin Anderson Avatar asked Jun 27 '14 18:06

Benjamin Anderson


People also ask

What is the difference between a string literal and a string object in JavaScript?

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.

Is string object or primitive?

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.

Which method evaluates a string of JavaScript code in the context of the specified object?

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.


2 Answers

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"
like image 170
Sterling Archer Avatar answered Sep 20 '22 12:09

Sterling Archer


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"
like image 42
Marc B Avatar answered Sep 17 '22 12:09

Marc B