M.J. Saedy
M.J. Saedy

Reputation: 336

How to detect syntactical features of JavaScript?

I know that feature detection works for sniffing objects and methods (things like JSON, querySelector,...) but what about new syntax? like default function parameters? The problem is that they cause a syntax error that cannot be caught.

Any insight on this? apart from browser and version sniffing which is mostly unreliable.

And if there is no way, does this mean we can not use new features! what are they for then (maybe for use after 10 years !)

Upvotes: 0

Views: 76

Answers (3)

JLRishe
JLRishe

Reputation: 101690

As icktoofay demonstrates, there are ways to check for syntactical features without causing a syntax error, but even if you do that, what would you do with that information? You would need to have multiple versions of your code depending on the supported syntax features and need to do dynamic loading of your scripts for no real purpose.

To address your last question, you don't necessarily have to wait to use the new features. You can use a JavaScript-next to JavaScript-of-today compiler like traceur-compiler, or Typescript, which includes future JavaScript features and compiles into browser-friendly JavaScript.

Upvotes: 3

LetterEh
LetterEh

Reputation: 26696

There is no reliable way to check general support for syntax errors.

However there is plenty that can be used in NodeJS, today. Also, there's nothing preventing you from using a transpiler, like Traceur, to write fancy JS and have it come out ES5-compatible on the other side.

Upvotes: 0

icktoofay
icktoofay

Reputation: 129001

Try to create a function within a try-catch block.

var code = '"forgotten close quote';
var valid = true;
try {
    new Function(code);
}catch(exc) {
    valid = false;
}

Here, trying to put "forgotten close quote into a function will fail due to a syntax error, which is then caught and will set valid to false.

Upvotes: 3

Related Questions