addyosmani / es6-equivalents-in-es5 Goto Github PK
View Code? Open in Web Editor NEWWIP - ES6 Equivalents In ES5
WIP - ES6 Equivalents In ES5
'use strict';
// define favorite as a non-writable `constant` and give it the value 7
Object.defineProperties(window, {
favorite: {
value: 7,
enumerable: true
}
});
// ^ descriptors are by default false and const are enumerable
var favorite = 7;
// Attempt to overwrite the constant
favorite = 15;
// will still print 7
console.log('my favorite number is still: ' + favorite);
The whole code run in browser result in 15, which may be caused by hoisting of 'favorite'. Maybe You can delete
var favorite = 7;
to fix it.
I guess...
In Node/CommonJS when you require('lib/math')
you are requiring math.js
from a module named lib
. This can be a point of confusion for newbies since it seems like you are requiring from a local path.
var math = require('lib/math');
console.log('2π = ' + math.sum(math.pi, math.pi));
The above might be clearer if it used either of these require paths:
require('./lib/math.js') // local path
require('lodash/array/chunk.js') // node_modules path
Some of the examples log out using strict equivalence, which could be misleading, as they general log as false
. Is there a reason the examples use this format?
// Object Initializer Shorthand
'use strict';
function getPoint() {
var x = 1;
var y = 10;
return { x: x, y: y };
}
console.log(getPoint() === {
x: 1,
y: 10
}); // false
console.assert(binary === [0, 1, 3]);
This will always be false, as [0,1,3]
is a new array literal and so won't equal anything preexisting.
It'd technically be more like (function(){ ... }.call(this))
. And some care of course taken in the arguments
department, but that's not so trivial to change without touching the actual code as well.
Another nit; if you're going for defineProperty anyways, you could define a getter/setter to throw on set and mimic the ES6 semantics more closely.
I believe the module docs are incorrect. Based on this lib/math.js
export function sum(x, y) {
return x + y;
}
export var pi = 3.141593;
The docs say we can import like this
import math from 'lib/math';
console.log('2π = ' + math.sum(math.pi, math.pi));
But I think this is incorrect. In this case math is undefined
because there is no default export. The correct import would be:
import * as math from 'lib/math';
or if you wanted to just destructure:
import { pi, sum } from Math;
I made this mistake today when dealing with code that was mixed with requires and import. These two statements below look equivalent because they similar structure which I think leads to the confusion:
var math = require('lib/math');
import math from 'lib/math';
There's a great reference here: http://www.2ality.com/2014/09/es6-modules-final.html for anyone who happens to come across this issue.
I realize array comprehensions were removed from es6, apparently due to es7 being performance oriented, including parallelism.
BUT Coffeescript has made me addicted to the critters! Would it be out of scope to show an example, in es6, of building your own array comprehension, then ditto for es5? They may be the same, sigh.
I think that the es5 example code in the rest parameters section can be shortened.
AS is :
"use strict";
function f(x) {
var y = [];
for (var _key = 1; _key < arguments.length; _key++) {
y[_key - 1] = arguments[_key];
}
// y is an Array
return x * y.length;
}
console.log(f(3, "hello", true) == 6);
// -> true
To be :
function f(x){
return x * (arguments.length - 1);
}
console.log(f(3, "hello", true) == 6);
Did you write some complicated code deliberately to let es6 syntax be emphasized?
A fat arrow function binds to the local execution context differently. Execute the following in FF:
var __slice = Array.prototype.slice;
var extendWithFunc = function (fn, obj) {
return fn.apply(obj, __slice.call(arguments, 2));
};
var myExtend = () => {
this.newData = __slice.call(arguments, 0);
return this;
};
var newObj = extendWithFunc(myExtend, {some: "object"}, "a", "b", "c");
Notice that if you inspect the value of 'newObj' it is Window. This is because the fat arrow does something much closer to a .bind(this) behind the scenes. Inside of 'extendWithFunc', the function application is ignored (because .bind() uses a special [[Call]] and [[BoundThis]] that cannot be overridden). Therefore, when 'myExtend' is called, the 'this' is the execution context of the global where 'myExtend' was defined (which happens to be Window).
Implementing fat arrow in ECMAScript5.1 as the following is probably closer to accurate.
[1, 2, 3].map(function(n) { return n * 2; }.bind(this));
According to the draft spec from mozilla http://people.mozilla.org/~jorendorff/es6-draft.htm
14.2.17 Runtime Semantics: Evaluation
ArrowFunction[Yield] : ArrowParameters[?Yield] => ConciseBody
NOTE Any reference to arguments, super, or this within an ArrowFunction are resolved to their bindings in the lexically enclosing function. Even though an ArrowFunction may contain references to super, the function object created in step 4 is not made into a method by performing MakeMethod. An ArrowFunction that references super is always contained within a non-ArrowFunction and the necessary state to implement super is accessible via the scope that is captured by the function object of the ArrowFunction.
Is there a reason to prefer forEach over filter ?
var fives = [];
var nums = [1, 2, 5, 15, 25, 32];
nums.forEach(v => {
if (v % 5 === 0)
fives.push(v);
});
over
var nums = [1, 2, 5, 15, 25, 32];
var fives = nums.filter(v => v % 5 === 0 )
I think this way is better:
'use strict';
function greet(msg, name) {
msg = msg || "hello";
name = name || "world";
console.log(msg, name);
}
greet();
// -> hello world
greet('hey');
// -> hey world
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.