Bad constructs – the eval statement

Another bad one is the eval() statement. This statement is not only very inefficient, but it is, most of the time, useless. Indeed, it is often believed that using the eval() statement is the proper way to deal with a provided string. But this is not the case. You can simply use an array syntax to do the same thing. For example, we could use the eval() statement in the following way:

function getObjectProperty(oString){    let oRef;    eval("oRef = foo.bar.baz." + oString);    return oRef;}

To get a substantial speed increase (from 80% to 95% faster), you could replace the previous code with the following:

function getObjectProperty(oString){    return foo.bar.baz[oString];}

Get Mastering The Faster Web with PHP, MySQL, and JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.