The only way to feature-detect a new syntax or keyword, is to eval
it (or, pass it to the not-much-better Function
constructor):
function detectLet(){
try{
return !!new Function('let x=true;return x')()
}catch(e){
return false
}
}
console.log(detectLet())
But also note that you can't conditionally use a new syntax, or try to catch a syntax error, since syntax errors happen before your code starts to run!
So, to conditionally use such a feature, you also need eval
, which is even worse...
if(detectLet()){
let foo = 'bar';
}
//SyntaxError if `let` isn't supported
if(detectLet()){
eval("let foo = 'bar';") //Wait... really?!
}
//No errors
Conclusion:
If you need to support (those really old) platforms, that don't support let
, then don't use let
.
Alternatively, you can transpile your code with tools like Babel
But as of 2022, all major browsers support let
(even IE!!!), so you can use it safely, and drop support for really legacy browsers.