user2672288
user2672288

Reputation:

eval returning undefined, browser returning a result

I've got a javascript string such as the following:

"h" + "e" + "l" + ("foo", "bar", "l") + ("abc", "def", "o")

If I save the string to a variable and eval it, it returns as undefined:

var str = "h" + "e" + "l" + ("foo", "bar", "l") + ("abc", "def", "o");
var x = eval (str);
console.log(x) // undefined

However, if I paste the string into the Chrome JS console, it returns as expected:

"hello"

Any reason why eval would return undefined, and how is the JS console accomplishing the feat?

Thanks!

Upvotes: 0

Views: 2576

Answers (2)

volx757
volx757

Reputation: 163

When you paste the string into the console, it immediately evaluates the operations you have defined, thus you get the proper

"hello"

result. When you go to eval, however, you should see "ReferenceError: hello is not defined." This is because the string operations have again been immediately resolved, so your call to eval becomes

eval('hello')

which is meaningless.

Upvotes: 0

Quentin
Quentin

Reputation: 943220

The expression "h" + "e" + "l" + ("foo", "bar", "l") + ("abc", "def", "o") evaluates as the string "hello".

If you paste that into the Chrome console, then you get what it evaluates to displayed.

If you pass it to eval then the expression evaluates to the string "hello" and then eval takes that string and evaluates to the variable name hello which isn't defined.

If you just want to get "hello" into a variable, then don't use eval, use an assignment.

var x = "h" + "e" + "l" + ("foo", "bar", "l") + ("abc", "def", "o");
console.log(x);

Upvotes: 2

Related Questions