Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 923
zomega Avatar asked Dec 08 '22 11:12

zomega


2 Answers

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.

like image 94
FZs Avatar answered Dec 28 '22 16:12

FZs


Despite its evilness, you could use eval() in this case, as long as you're not evaluating any user input. Wrap it in a try/catch statement and you can check whether it throws a syntax error or not.

Syntax errors themselves are not catchable, therefore you cannot simply add a try/catch statement around a let statement.

I added an example using an imaginary "foobar" keyword for demonstration purposes:

var canLet = false;
try {
  eval('let foobar = "baz";');
  canLet = true;
} catch (e) {}

console.log("this browser does" + (canLet ? '' : ' not') + " support the let keyword");

var canFoobar = false;
try {
  eval('foobar baz = "bar";');
  canLet = true;
} catch (e) {}

console.log("this browser does" + (canFoobar ? '' : ' not') + " support the foobar keyword");
like image 44
Constantin Groß Avatar answered Dec 28 '22 15:12

Constantin Groß