Skip to content Skip to sidebar Skip to footer

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 undef

Solution 1:

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 namehello 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);

Solution 2:

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.

Post a Comment for "Eval Returning Undefined, Browser Returning A Result"