JavaScript – Understanding Dynamic Code Evaluation

javascript

The following is from the preface of Jon Resig's new book : Secrets of JavaScript Ninjas

The portions of this book that cover features that are relatively un-changing, such as code evaluation, with statements, and timers are continually being used in interesting ways. There are now a number of active programming languages that are built on top of, or compiled to, JavaScript: Such as CoffeeScript or Processing.js. These languages require complex language parsing, code evaluation, and scope manipulation in order to work effectively. While dynamic code evaluation has been maligned due to its complexity and potential for security issues, without it we would not have had the CoffeeScript programming language – which has gone on to influence the upcoming ECMAScript specification itself.

I’m personally making use of all of these features, even today, in my work at Khan Academy. Dynamic code evaluation in the browser is such a powerful feature: You can build in-browser programming environments and do crazy things like inject code into a live runtime. This can result in an extremely compelling way to learn computer programming and provide all sorts of capabilities that wouldn’t be possible in a traditional learning environment.

What is actually "Dynamic code Evaluation" ? What are its benefits ? Please illustrate with a nicely contrived example .

Best Answer

Dynamic code Evaluation means "executing code within code" -- the first 'code' is represented by strings in the second 'code'.

Non-compiled languages provide some way of executing code from within a program. All the steps (parsing, intermediate code generation, optimization, etc.) are executed on the fly for the dynamically processed code.

Dynamic code Evaluation comes in handy specially when you can not write code without some variables that are only available on run-time. See an example in this question.

Another advantage is debugging. You can write custom debuggers that can execute code at a specific break point while the program is on the go.