How to check if 'let' is supported by the browser?

Issue

What is the best way to check if my browser supports the let command to declare a variable valid only for the current code block?

This is not a duplicate of question What browsers currently support JavaScript’s ‘let’ keyword? because the question refers to a non-standard syntax extension in FF, and the eval/Function solution was not posted.

I need to perform this check to redirect users with old browsers to a site advising them to update their browser.

Solution

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.

Answered By – FZs

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.