0

In function code, when I do this:

eval( 'var default = 100;' );
alert( default );

the browser's JS engines* will throw a Syntax Error on the second statement, as if the first statement executed successfully.

See here: http://jsfiddle.net/4FMdy/ (open the browser's console to view the error log)

However, when I remove the second statement from the code, so that I only have this:

eval( 'var default = 100;' );

the browser's JS engines will throw a Syntax Error on that statement.

See here: http://jsfiddle.net/4FMdy/1/

I don't understand this. If the first statement throws a syntax error (as it should), why does only the second statement throw such an error in my first example above. From what I understand, if a statement throws an error, that necessarily means that all previous statements (of the same call) executed successfully.

Btw, the syntax error is thrown because default is a reserved word in JavaScript, so it cannot be used as a variable name.

Also, no "eval is evil" comments please. I'm just trying to understand the behavior of the browser's JS engines.

* I tested in Firefox, and Chrome

2 Answers 2

2

Just an assumption:

The script-block first will be parsed, but not executed(the eval)

The browser detects only the syntax-error in line#2 and didn't execute complete script-block, so he will not determine the syntax-error in eval()

When you put the 2 lines in 2 different script-element you'll receive both errors:

http://jsfiddle.net/doktormolle/CfRmj/

1
  • Yes, that's it. Now I understand. The stream of tokens first has to be parsed into a Program, and only then the resulting program is evaluated. Info in second paragraph here. The tokens alert, (, default, ), and ; are not a valid sequence according to the syntactic grammar. So, the program is not valid, and is therefore not evaluated at all. Any syntax error that would appear in the string passed to eval() could only be detected once the program is being evaluated, which is after it has been parsed according to the syntactic grammar. Sep 13, 2012 at 14:28
0

Because "default" is Javascript reserved keyword :)

So alert(default) throws "syntax error" if code is checked if is correct, but then the function eval is runned, and process wount get here because of first error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.