[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.javascript

eval is like typeof, for potentially unsupported syntax

lewisje

12/29/2014 9:51:00 AM

Just as "if (typeof x !== 'undefined')" is used to ensure that x is declared and not the undefined value because "if (x !== undefined)" would cause a ReferenceError if x were not declared, eval can be used to test whether the browser supports the new syntax in ES6 and later, without causing the script to fail completely in browsers that don't support the new syntax.

One good use case is testing support for "let"; this JSFiddle shows how it works, and the key scripts are re-typed below (I know that in Chrome 39 with experimental Javascript features enabled, the let statement is supported in strict mode only, which is why I made both tests): http://jsfiddle.net...

function testLet() {
try {
eval('let b = 3;');
}
catch (e) {
return false;
}
return true;
}

function testLetStrict() {
'use strict';
try {
eval('let b = 3;');
}
catch (e) {
return false;
}
return true;
}

I know that if you remove the eval in those cases where the syntax is *not* supported, and just use a bare statement instead, the script breaks (even if you never invoke the function), so you can't just if around it or use a try block and catch the error; it looks like you need to put the statement with potentially unsupported syntax in a string and eval it inside a try block.

In practical situations, something like this would be used in a scheme of syntax detection, akin to the common use of feature detection, to determine whether to load a proper ES6 script or a version that had been compiled to ES5.

I have not read about this particular use case before, but I have a hard time believing that I'm the first to have found it; in particular, I didn't notice it in Axel Rauschmayer's explanation of eval and its relatives (like new Function() and passing strings to setTimeout, setInterval, or setImmediate): http://www.2ality.com/2014/01...
1 Answer

lewisje

12/30/2014 5:14:00 PM

0

On Monday, December 29, 2014 4:50:54 AM UTC-5, lew...@gmail.com wrote:
> I have not read about this particular use case before, but I have a hard time believing that I'm the first to have found it

Indeed, just today I found something like this, from three years ago, while looking up the yield statement, although the use of the Function constructor instead of a function expression inside the eval'd string looks like bad form: https://stackoverflow.com/questions/2297286/javascript-check-yield-support/72495...