3

Just testing for const support in browsers, so I need to catch syntax errors, which you can only do with eval.

var const_support = true;
try{
    eval("const test = 'test';");
}
catch(e){
    if (e instanceof SyntaxError) {
        const_support = false;
    }
    else{
        throw ("Something crazy happened.");
    }
}

Cheers.

Edit: Sorry for duplicate. Like epascarello solution better anyway. Avoids eval.

Peach Passion
  • 457
  • 3
  • 11
  • 2
    This method is how features are tested for on this site: http://kangax.github.io/es5-compat-table/es6/ – gen_Eric Feb 19 '14 at 15:39
  • 1
    The supposed "duplicate" doesn't mention anything about this reason for using eval. Not a duplicate – Gareth Feb 19 '14 at 15:41
  • 1
    Why not new Function? `var x = new Function("const test = 'test';"); try { x(); }...` – epascarello Feb 19 '14 at 15:43
  • 2
    @Gareth: I disagree, the reason wasn't the question. The question was "is it safe" and the linked dupe answers that question. If the question was "how do I test for `const` support" then the suggested dupe wouldn't apply. – Matt Burland Feb 19 '14 at 15:48
  • @MattBurland Fair point – Gareth Feb 19 '14 at 15:49
  • I don't see anything wrong with it. So far as I am aware, `eval` is only unsafe when used to parse code from an unknown source. This seems to me like a clever use of it. – Mild Fuzz Feb 19 '14 at 15:54
  • If `eval()` is the answer, you definitely asked the wrong question. `eval()` is NEVER the best (or only, for that matter) solution... – BenM Feb 19 '14 at 16:13

0 Answers0