Destructuring in ES6. Should I worry? - javascript

Experimenting with destructuring and found that the same code works on stackoverflow and not Codepen (toy gets "undefined"): http://codepen.io/tsalexey544/pen/VjWxmm?editors=0010#
What does it mean? should I worry when using destructuring in my projects?
let obj = {
species: "Cat",
// toy: "ball",
}
function whatDoTheyDo ({species, toy = "ball"}) {
return `The ${species} playes with a ${toy}`
}
document.write(whatDoTheyDo(obj));

You just need to set the Preprocessor to babel in CodePen, otherwise it will use standard ES5, where destructuring is not supported.
If you want to use ES6/ES7 features you have to "transpile" your code back to ES5 using certain tools such as Babel. Some browsers already support some ES6 features, but full support is still somehow spotty.
Edit - To answer your question: YES, you should worry about serving valid ES5 code, since ES6 is not yet fully supported. At the very minimum you should feed your code to Babel and publish the resulting code, but I strongly suggest looking it Webpack and going for a full toolchain

Related

nightwatch-cucumber ES6 --- nightwatch JS ES5

I've read that nightwatch does not support ES6. Fair enough.
However, the documentation for nightwatch-cucumber
Looks like it uses ES6 (arrow functions) on the steps it defines as examples.
My question is: Is it possible to use ES6 on the cucumber steps and ES5 on the page objects for nightwatch? Or should I stick to ES5 for everything?
Yes I was able to write my cucumber steps in ES6 and my page objects in ES5. However it might be better to stick to ES5 to have consistency + I did notice I would get some strange failures (rarely) when using:
Given('Go to Site', () => client.url('https://google.com'));

How to use babel to transform es6 to es5 programmatically?

I have a function which runs string as javascript code through eval(). It works fine if the string is es5 but doesn't work for es6. I know babel can transport es6 to es5 but most of them use cases are done in compile stage. How can I use babel programmatically?
Babel has an API.
I assume you can do something like this:
eval(babel.transform(code, options).code)
However I would strongly reconsider that! First, eval is usually a very, very dangerous thing, and next babel is huge. You don't want to deliver that to a browser if you don't have to.

How to get rid of editor’s error for object.key

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])
}
});

So i'm using Javascript const keyword, what happens in IE?

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.

How can I use decorators today?

I see decorators being used today already in some javascript code. My question is really two fold.
First:
If decorators have not even been finalized how is it possible to use them in production code, today? Won't browser support be non-existent?
Second:
Given it is possible to use it today, as some open source projects would suggest, what's a typically recommended setup for getting decorators to work?
You're right, ES2016 decorators are not yet part of the spec. But it doesn't mean we can't use it today.
First let's take a step back and go over "what is a decorator". Decorators are simply wrappers that add behavior to an object. It's not a new concept in javascript (or programming in general), it's actually been around for a while...
Here's a basic example of a decorator that checks permissions:
function AuthorizationDecorator(protectedFunction) {
return function() {
if (user.isTrusted()) {
protectedFunction();
} else {
console.log('Hey! No cheating!');
}
}
}
Using it would look like this:
AuthorizationDecorator(save);
You see all we're doing is simply wrapping up some other function. You can even pass a function through multiple decorators each adding a piece of functionality or running some code.
You can even find some old articles explaining the decorator pattern in javascript.
Now that we understand decorators are actually something we (javascript community) were always able to do, it probably comes as no shock that really when we utilize ES2016 decorators today they are simply just being compiled down to ES5 code hence why you maintain browser compatibility. So for the time being it is simply syntactic sugar (some really sweet sugar I might add).
As for which compiler to use to convert your ES2016 code to ES5 code, you have some choices: Babel and Traceur are the most popular.
Here's further reading on Exploring ES2016 Decorators.
#Class decorators support can be enabled in Babel/Traceur
Babel:
$ babel --optional es7.decorators
Source: Exporing ES7 Decorators - Medium
Traceur:
traceurOptions: {
"annotations": true
}
#Property decorators are not supported
...and since each #Property provides a unique functionality, each requires a different approach to desugaring in ES6/7.
Here's how you use #Inject:
Typescript
exports class ExampleComponent {
constructor(#Inject(Http) http: Http) {
this.http = http;
}
}
ES 6/7
exports class ExampleComponent {
constructor(http) {
this.http = http;
}
static get parameters() {
return [[Http]];
}
}
Source: https://stackoverflow.com/a/34546344/290340
Update:
It looks like Babel changed the way decorators are configured and the article is out-of-date. Here's a link to the new approach.
In short; yes you can use #Class decorators in ES6/7; no property decorators aren't supported in ES6/7 so you'll have to use workarounds.
There are some solutions to use decorators:
babel - an es next to es5 compiler with support of decorators.
traceur - another es next to es5 compiler by google.
typescript - a typed superset of javascript language that supports decorators.
There are some difference how these tools transpile a "modern" javascript to an older one so you can explore it if needed as they have online playgrounds.

Categories

Resources