typeof ..keyword.. == "keyword"

sometimes as the language gets extended new keywords are added. I propose we extend the typeof operater to return "keyword" if a literal is a keyword. This can help scripts/modules/programs determine what specific language features are available when those scripts might be called in different contexts.

e.g.
typeof for // returns "keyword"
typeof default // returns "keyword"

I'm pretty sure new keywords are rarely added, but when they are, I believe it'd have to be in a context that would previously have been a syntax error.

For example, typeof for is a syntax error. I don't think anything syntactic is viable for feature detection purposes; the thing you'd do right now is use try/catch around Function. The improvement I'd want on top of that (and that's been requested in the past) is an API that does not require syntax, but can achieve the same thing as Function without triggering CSP/eval warnings.

1 Like

Please consider things like "export" and "module" or "let" these got added in later versions. As deal with ES6 vs ES5 or future versions scripts will need to know about compatibility at runtime. Simple checks like this could be useful. Of course a large percentage of apps are built with transpilers (e.g. Babel, etc) it seems that simple checks like the suggested one could be useful for spot checks.

Here is a list of keywords be version to show just how dynamic this issue is:
https://mathiasbynens.be/notes/reserved-keywords

module isn’t a thing; export only works in the new Module script goal (it was a syntax error before, and still is one in a Script). β€œlet” is a fair point, but if you use it in any of the positions it’s valid in now, in an older environment, it will be a syntax error.

1 Like

Good points, but when dealing with js that could be loaded in multiple environments it allows that script (or the output of a transpiler) to quickly determine what run-time features are available. Perhaps there are better ways and as you point out one can always try - catch things. Perhaps the try-catch mechanism can be updated that if a syntax error is thrown the error in the catch can be keyword used.
But a nice thing about enhancing typeof (and this could be true for all future versions of js) is that it can provide useful information without throwing errors.

It would be nice if feature detection didn't essentially require transpiling. I come from an embedded systems assembly/C/C++ background where code is most often distributed in binary form after compilation and linked. In the js world code is effectively always distributed in source form. So the feature set available at time-of-writing may be different than runtime.