ECMAScript 2022 introduced await at the top level of a module. In older browser versions (eg Safari 14) it throws a syntax error. I would like to detect support for TLA so I can provide an alternative.
Since this is a syntax feature I tried to eval TLA in a try/catch-block. However this will always throw a syntax error, since await is only valid at the top level, not inside try and eval.
Related
I want to ensure that my output only contains "vanilla" javascript and does not contain new features (like const, map(), => etc.).
This is to ensure that the code still works on legacy browsers.
Is Node.js supporting => function keyword alias already? If yes, starting from which version? How to enable this language extension?
(function() { console.log('it works!') })()
Becomes
(() => { console.log('it works!') })()
In short: yes, arrow functions are reasonably well supported in Node.js since version 4.4.5.
Completely correct support starts with version 6. Initial support was introduced as far as v0.12 but is was very incomplete and disabled by default until v4.0 when it got better. See Node's ES6 compatibility table for details: http://node.green/#ES2015-functions-arrow-functions.
The syntax you're referring to is "arrow function" syntax. It is a feature of ECMAScript 6, also known as "Harmony". The ES6 standard is now finalized, but engines are still implementing its new features.
The V8 now has arrow function support. Node runs on the V8 engine, but it can take some time for Node to incorporate the latest version into its code base.
Whenever it is added, it might possibly be enabled only via a --harmony command-line flag.
You can follow this issue: https://code.google.com/p/v8/issues/detail?id=2700
Currently (as 02.05.2014) arrow functions have been implemented and waiting until this functionality will be landed in v8: https://codereview.chromium.org/160073006/
After then we'll need to wait, until v8 version with arrow function would be integrated into Node.JS. You can follow Node.JS changelog there: https://github.com/joyent/node/blob/master/ChangeLog (search for "v8: upgrade to ....")
kangax's compatibility tables can keep you up-to-date with what is currently available in Node.
Experimental features can be enabled using the instructions on this page:
All shipping features are turned on by default on Node.js
Staged feature require a runtime flag: --es_staging (or its synonym, --harmony)
In progress features can be activated individually by their respective harmony flag (e.g. --harmony_destructuring) but this is highly discouraged
I have the following code that basically gets some JSON data, looks for the keys with "servergenre", and saves the results in an array.
This is a follow up of this question.
let result = [];
Object.keys(data).forEach( key => {
if(/servergenre/.test(key)){
result.push(data[key])
}
});
Even though the code is working correctly, in some editors it raises syntactic errors:
"key": unsolvable variable or type key
"=>": expression expected
"if( / server...": formal parameter name expected
")){": , expected
"});": statement expected
Here is an image to show you where the errors are:
As I said the code is working fine, I just need it to be fixed or another approach to get rid of the errors.
Furthermore, many compressors and minifiers do not support this bit of code. So I can’t minify it.
Thanks in advance.
ES2015, formerly known as ES6, is a more recent version of JavaScript, which introduces features such as the => syntax for functions you are using.
Not all features of ES2015 are fully supported in all browsers, so many people who use it pass it through a compiler (“transpiler”) first to convert it to ES5, which is supported by all browsers. Babel is one such transpiler. But if you are only targeting newer browsers, that would explain why the => syntax is working for you.
You just need to change your editor settings to understand that syntax. Exactly how you do that depends on what text editor you are using. It could be that your editor's built-in JavaScript mode doesn't know how to read ES2015 syntax, and you need to either upgrade your editor or install a third-party plugin that provides an updated error-checker. Or it could be that your editor supports both ES5 and ES2015, and it thinks you are trying to write your project only in ES5. In this case you just need to go to the settings and tell your editor that you mean for this project to use ES2015 (or ES2016, which is currently the most recent version).
Fat arrows are ES6 syntax. If that causes trouble, just write good old ES5 :
let result = [];
Object.keys(data).forEach( function(key) {
if(/servergenre/.test(key)){
result.push(data[key])
}
});
I understand that the const keyword has been already implemented across the board in browsers except for IE10 versions, but is it viable? If someone jumps on my site on IE10< will the "const" keyword be re-assigned to "var"? if not will the whole site fail? the MDN docs on the const keyword give a handy chart at the bottom which tells me that not only IE, but rather many Mobile browsers do not support it either. should i just scrap it and use var?
Take Babel, the ECMAScript 2015 (ES6) to ECMAScript 5 transpiler.
If you write:
const a = 123;
It outputs:
"use strict";
var a = 123;
If the potential of breaking your code on unsupported browsers isn't enough, i think that should be.
IE11 and above supports const but IE10 and below do not.
If you attempt to use const in any browser that does not support it, you will get a syntax error. If you must support older browsers, you cannot use const unless you use a transpiler to compile your code down into ES5. Babel is a good example of such a transpiler.
If you want to write clean ES6 (ES2015) code using const you could use JS compiler like Babel. For example:
const a = 1;
it recompile to
"use strict";
var a = 1;
If you want painless babel configuration use this yeoman babel generator.
I'm toying with let in Node v0.10.12. Using the --harmony flag the following code produces a syntax error:
for (let i = 0; i < 2; i += 1) {
console.log('i', i);
}
SyntaxError: Illegal let declaration outside extended mode
However, if I also use the --use-strict flag, then the code runs as expected.
Why is a syntax error thrown when just using the --harmony flag? What is extended mode? What is the connection with strict mode?
It looks like "extended mode" was removed from the current development version of the harmony spec on February 27, 2012, but there's a description of what it was supposed to be in a few older ones (this one is from January 16, 2012):
10.1.2 Extended Code
Extended code is any code contained in an ECMAScript Program syntactic
unit that contains occurrences of lexical or syntactic productions
defined subsequent to the Fifth Edition of the ECMAScript
specification. Code is interpreted as extended code in the following
situations:
Global code is extended global code if it is contained in an ECMAScript Program syntactic unit that has been designated as an
extended Program unit in an implementation defined manner or if ???.
Eval code is extended eval code if the call to eval is a direct call (see 15.1.2.1.1) to the eval function that is contained in
extended mode code or if it begins with ???.
Function code that is part of a FunctionDeclaration, FunctionExpression, or accessor PropertyAssignment is extended function code if its FunctionDeclaration, FunctionExpression, or
PropertyAssignment is contained in extended mode code or if the function code begins with ???.
Function code that is supplied as the last argument to the built-in Function constructor is strict function code if the last argument is a
String that when processed as a FunctionBody begins with ???.
The term “strict code” is used to designate both actual strict mode
code and extended code while the term “extended code” only designates
actual extended code. The term “base code” is used to designate code
that is not extended code.
As for the connection with strict mode, that seems to be specific to V8's (experimental) implementation. Here's what the changelog for revision 10062, which introduced the --harmony flag, says:
This CL introduces a third mode next to the non-strict (henceforth
called 'classic mode') and 'strict mode' which is called 'extended
mode' as in the current ES.next specification drafts. The extended
mode is based on the 'strict mode' and adds new functionality to it.
This means that most of the semantics of these two modes coincide.
The 'extended mode' is entered instead of the 'strict mode' during
parsing when using the 'strict mode' directive "use strict" and when
the the harmony-scoping flag is active. This should be changed once it
is fully specified how the 'extended mode' is entered.
How to obtain harmony in your node.js
The --harmony flag enables ES Harmony features. it seems that --harmony enables new ECMA features in the language, based on the v8, proxies, weak maps, sets, maps, typeof semantics, and block scoping are available when this flag is being used and these are extended features and after extending these features you can use for example let (for block scoping) with strict mode enabled only because it's based on it, otherwise it will throw
SyntaxError: Illegal let declaration outside extended mode.
Extended Mode : When you are using new ECMA features (ECMAScript 5), you are in the extended mode of the language and in this mode ECMAScript’s new features (extended code) and syntax could be used only in strict mode
Concept of “extended code” that means code that may use new Es.next
syntax.
Harmony :
"Harmony" is the name of the major upgrade to JavaScript due to arrive by the end of 2013. In 2008, after much controversy, the ECMA Technical Committee 39, that had been charged with creating the next generation of JavaScript, agreed to work together on a "Harmony" update to JavaScript and it has been in development since then.
A number of the proposed features of Harmony are supported by Google's implementation. These include block scoped bindings and the addition of the let keyword, efficient maps and sets to remove the need to "abuse objects as dictionaries", weak maps for garbage collectable key/value tables and proxies which can simulate any JavaScript object or function to enable customisation.
Some good reads here and hear. Also from Chromium Blog.
Also from Paul Irish :
François Beaufort (originally shared): A new flag named Enable
Experimental JavaScript appeared in the chrome://flags page of the
last Chromium build. This flag enables web pages to use experimental
JavaScript features.
To use extended mode/harmony features now in Chrome we have to enable this and we can enable this by navigating to chrome://flags and can toggle (enable/disable) on "Experimental JavaScript features".