FAQ Database Discussion Community


functional way to iterate over range (ES6/7) [duplicate]

javascript,ecmascript-6,ecmascript-harmony
This question already has an answer here: Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables? 5 answers What is the best way to do the below in more functional way (with ES6/ES7) let cols = []; for (let i =0; i <=...

Explanation of `let` and block scoping with for loops

javascript,ecmascript-6
I understand that let prevents duplicate declarations which is nice. let x; let x; // error! Variables declared with let can also be used in closures which can be expected let i = 100; setTimeout(function () { console.log(i) }, i); // '100' after 100 ms What I have a bit...

Executing promises in sequence: understanding a claim made about this example code

javascript,promise,ecmascript-6
I'm not looking for a solution for how to execute promises in sequence, I'm trying to understand the one given by a blog author: I am reading "We have a problem with promises" by Nolan Lawson, posted 18 May 2015. Under "Advanced mistake #3: promises vs promise factories" he has...

ES6 - Using babel/traceur with jQuery plugins

javascript,jquery,gulp,ecmascript-6,babel
I want to be able to write ES6 with jQuery plugins and compile the code down to ES5 using Gulp Babel, without having to use Browserify to make them work. For example, I may have a class like this: import $ from 'jquery'; import somePlugin from 'somePlugin'; class myClass {...

Is the Angular 2 @Component syntax part of ES6?

angularjs,typescript,ecmascript-6,angular2
Can anyone tell me. The '@' symbol in front of the imported Component function. Is that ES6 syntax? I've not seen it used on any other non-angular ES6 projects I've looked at. import {Component from ...} @Component({}) Here is a example...

How to use 'let' (and supported ECMAScript 6 features) in both Firefox and Chrome

javascript,google-chrome,firefox,ecmascript-6
ES6 script using let runs as expected in latest Chrome stable if it's inside a "use strict" definition. And it runs fine in Firefox if it is loaded using a script tag with the special type: <script type="application/javascript;version=1.7" src=""></script> But files with that special type now won't run in Chrome!...

ECMAScript class

javascript,ecmascript-6
I have the following code which when the web page loads should print the car make and current speed to the console. Nothing is printed to the console. If I put the new object declaration inside a function it does print either. <!DOCTYPE html> <html> <head> <script type="application/ecmascript;version=6"> class Car...

Can anyone explain what es7 reflect-metadata is all about?

npm,ecmascript-6,jspm,systemjs,es7
Been studying ES6, JSPM & angular2 for a week now and I found this repo ES6-loader if we look at the index.html at the bottom script you'll see System.import('reflect-metadata') .then(function() { return System.import('app/index'); }) .catch(console.log.bind(console)); This is using JSPM's systemjs polyfill to get ES6's import. Question: What is the reflect-metadata...

Object.is vs ===

javascript,ecmascript-6
I stumbled upon a code example which was using this comparison: var someVar = 0; Object.is(false, someVar); //Returns false I know false == 0 will be true that's why we have ===. How is Object.is different from ===? ...

How do I support jasmine and es6 syntax in Visual studio Code?

jasmine,ecmascript-6,vscode
Question where can I find and how do I add support for jasmine and es6 syntax in Visual studio code? ...

ES6 destructuring, dynamic assignment [duplicate]

javascript,ecmascript-6
This question already has an answer here: object destructuring without var 1 answer let text, value; if (typeof f == 'string') { text = value = f; } else { let { text, value } = f; } Doing this creates two new vars (from the else), however if...

Automatically call bind() on all instance methods in es6 during constructor

javascript,ecmascript-6
How can I (or is it possible to) make a JavaScript base class that automatically calls bind on each of its instance methods during it's constructor? I tried, without success: class BaseClass { constructor() { // for (let i in this.__proto__) { // <-- this also failed for (let i...

Create ES6 class from a function

javascript,ecmascript-6,ecmascript-harmony
I'm trying to explore using ES6 classes instead of how we do it currently, using the Function.prototype means. Currently our API looks like: var myclass = createClass('MyClass', { test : function() {} }); We iterate through the object and apply those properties onto the Function that we return, basically a...

Using String.raw() with Node JS

javascript,node.js,ecmascript-6
I'm working on a Node.js app with and I would like to use String.raw() which is part of the ES 6 standard. However, when using it as in the documentation: text = String.raw`Hi\n${2+3}!` + text.slice(2); It returns SyntaxError: Unexpected token ILLEGAL for the character after String.raw. I think that there...

Javascript ES6 generator async

javascript,generator,ecmascript-6
I need to run generator async (I need to have result in console 1,2,3,4,5 cause now I have 4,1,2,3,5) any one can help me? I need run task and wait when previous task is finished before it run next task. I need to use (if possible: only) generators (or generator...

ECMA 6 postfix condition use-cases

javascript,coffeescript,ecmascript-6
I was reading the following presentation, and somewhere towards the end it mentions Postfix Conditions to be introduced in ECMA6 script. It provides he following use-case scenario: console.log("42") if question is true; I searched Google for more use-case scenarios and potential advantages to regular conditions. What was the reason for...

When should I use yield and when yield* with Koa.js

javascript,node.js,ecmascript-6,koa,yield-keyword
Browsing through koa samples, docs and middleware, I noticed both forms of yield are being used without any particular difference i noticed. The most extreme case is in koa-mount, where the sample code uses the yield next; form, and the package itself uses yield* several times. Other packages (koa-views for...

string.includes('a') function not defined in Node.js 0.12?

node.js,ecmascript-6
I do understand the includes() array-function is only supported for ECMAscript 6+, but isn't ECMAscript 6 now already supported in Node.js? I've also tried to run: node --harmony app.js but that gave me an: node: bad option: --harmony On my Windows 8 machine. I've also tried to use string.contains('a'); but...

What is the correct (spec-wise) behavior of `yield* undefined` & `yield undefined` in ES6?

yield,ecmascript-6,babeljs,traceur
While trying to understand how to work with KoaJS (question), I came to realize that yield* undefined behaves differently between babel & traceur. Babel seem to ignore the statement, while traceur throws an exception. A sample can be seen here: Babel - Traceur. I tried looking it up in the...

Using Istanbul and Mocha to cover ES6 code

node.js,code-coverage,mocha,ecmascript-6,istanbul
I have Node code, written in ES6, that I test by issuing mocha --harmony. Tests are fine - everything works. Now I want to add coverage and istanbul to the mix, but I keep getting errors on the first arrow function encountered: No coverage information was collected, exit without writing...

const variable not hoisted for immediately invoked function

javascript,scope,const,ecmascript-6,hoisting
I was playing around new ECMASCRIPT-6 const key word. I did not understand one particular behaviour of the keyword. Lets say I have two functions First case (function(){ console.log(_t); const _t=10; })(); and Second case function t(){ console.log(_y); const _y=11; } t(); For the first case the output is (didn't...

Javascript - Base class method not available in derived class when extending using lodAsh

javascript,ecmascript-6,lodash
I have a base class : class Base { constructor() { this.name = "base_class" } getBaseName() { return "base" } } and a Derived class var _ = require('lodash'); class Derived { constructor() { this.name = "derived" } getDerivedName() { return "derived" } } _.extend(Derived.prototype, Base) I was expecting to...

Change the value of a key in ES6 constructor

javascript,class,prototype,ecmascript-6
Question: How do I write a proper prototypical function using classes in ES6? How do I make sure that this function will change the value of title key in the constructor of Todo class? class Todo{ constructor(title){ this.title = title; } setTitle(newTitle){ this.title = newTitle; } } var a1 =...

Input validation setTimeout in ReactJS

javascript,css,validation,reactjs,ecmascript-6
I have a component that renders with className="error" or classname="" depending on whether the input is valid or not. This way in CSS I can simply do .error { background: red; }. The validity of the input is determined by the isValidNumber(..) function. However, right now the problem I'm having...

can es6 class have public properties as well as functions?

javascript,class,properties,public,ecmascript-6
All the examples of classes I see are class myClass{ constructor(){} someFunction(){} what I want to add is someObject {myvalue:value} } this doesn't seem to compile. An old fashioned object would be { somefunction: function(){} someProperty: {myvalue:value} } is this not possible in es6 classes?...

How to check if a variable is an ES6 class declaration?

javascript,class,prototype,ecmascript-6
I am exporting the following ES6 class from one module: export class Thingy { hello() { console.log("A"); } world() { console.log("B"); } } And importing it from another module: import {Thingy} from "thingy"; if (isClass(Thingy)) { // Do something... } How can I check whether a variable is a class?...

Babelify omit file extension on import

reactjs,browserify,ecmascript-6,babel
I am writing a React application with ES6 and JSX. Below is the command I use to browserify my .es6 files into a bundle.js. $ browserify src/es6/app.es6 -t babelify -o build/js/bundle.js When I try to import a component using something like import MenuBar from './menu', I get the error message:...

Import non modular scripts (linq.js) in Aurelia

ecmascript-6,aurelia
I have a question about importing script which define global variables to aurelia using import keyword. We can simple import modules but what about scripts like linq.js which define global variable Enumerable? Is this possible to execute that script to define that namespace? I tried to do steps from this...

Aurelia update value of bound item in another class

ecmascript-6,aurelia
I guess the question boils down how to i pass the instance of a property to another class. I have something like this: import timerClass from "./timer"; export class App { constructor() { this.timeLeft = 6; //<--- I want to update this new timerClass(this.timeLeft); } activate() { } } and...

setState() inside of componentDidUpdate()

javascript,reactjs,ecmascript-6
I'm writhing a script which moves dropdown below or above input depending on height of dropdown and position of the input on the screen. Also I want to set modifier to dropdown according to its direction. But using setState inside of the componentDidUpdate creates an infinite loop(which is obvious) I've...

How to properly bind current object context in ES6 using babelify

ecmascript-6,babel
I'm trying to bind current instance to the class method, please note ES6 syntax. class SomeClass { search() => { ... } } Which is 100% legit code, however babelify doesn't want to compile it SyntaxError: /Users/vladmiller/Projects/test/test/client/test/app/pages/Search.react.js: Unexpected token (50:26) while parsing file: /Users/vladmiller/Projects/test/test/client/test/app/pages/Search.react.js\ Instead now I have to bind...

Why doesn't my Deferred run the error method?

javascript,promise,ecmascript-6
I have created this simple code to simulate resolve , reject , error : function $http(){ var core = { factory : function (action) { var promise = new Promise( function (resolve, reject) { if (action==='resolve') resolve({r:'Resolved'}); if (action==='error') throw Error("error"); if (action==='reject') reject({r:'Reject'}); }); return promise; } }; return...

Importing modules using ES6 syntax and dynamic path [duplicate]

javascript,node.js,module,ecmascript-6
This question already has an answer here: ES6 variable import name in node.js? 2 answers This works: import app from './../app.js'; But this doesn't: import app from path.join(process.cwd(), 'app'); I'm Getting: SyntaxError: /path/file.js: Unexpected token (5:16) > 5 | import app from path.join(process.cwd(), 'app'); | ^ It is possible...

Do I have to call super.componentDidUpdate in React?

reactjs,ecmascript-6
In a subclass of React.Component, do I have to call super.componentDidUpdate from my componentDidUpdate method? Or is it done automatically? (I am trying to call it but there is an error message Cannot read property call of undefined)...

how to correctly use promises to return 2 different results [duplicate]

javascript,promise,ecmascript-6,es6-promise
This question already has an answer here: How do I access previous promise results in a .then() chain? 6 answers I am trying to use Promises in JavaScript using ES6 to return data from 2 methods from an object, which would in production call out to an endpoint. My...

Sequential Loading Using Promises

javascript,promise,ecmascript-6,bluebird,es6-promise
I've got an array of asynchronous calls that I want to be called sequentially, meaning that I don't want to call the second promise until the first is complete, and so on. In the following example, I've got a loop that creates unique images on the fly and appends them...

Is the window.System object a required part of JavaScript ES6

javascript,specifications,ecmascript-6
A while back I read that the System object is a required part of es6 modules, basically a new Object type with all the required semantics for module loading. Is this a strict es6 requirement? It doesn't seem to be in the latest spec....

Shallow-clone an ES6 Map or Set

javascript,ecmascript-6
How do you shallow-clone an ES6 Map or Set object? I want to get a new Map or Set that has the same keys and values....

ES6 global import

javascript,module,ecmascript-6,ecmascript-harmony
What is the best way to import some modules in all of the files of the project, so I don't have to write stuff like: import React from 'react'; import Reflux from 'reflux'; import reactMixin from 'react-mixin'; in almost every single file?...

Obj-C category/extension Swift in Javascript ES6

javascript,ecmascript-6
I'm looking to add methods to a class in Javascript ES6 without creating a subclass of it, in the same way with the categories in Objective-C or extensions in Swift. I didn't find any information about it. Any suggestion?...

Writing the most basic Unit test in Angular 2?

javascript,unit-testing,karma-runner,ecmascript-6,angular2
Problem: As soon as I import Angular 2 into a file none of my tests execute. Question: How can I set up my karma config to support angular two so my test pass properly? OR Question: How can I set up any testing framework with angular2 written in es6? Git...

Attempted to assign to readonly property ECMAScript React Native

ecmascript-6,react-native
I am trying to assign a value to an array declared in my Component. Unfortunately, exception is thrown. TypeError: Attempted to assign to readonly property Even if I remove strict mode, still exception is being raised. Can please someone guide me how can I make a variable both readable and...

How to get a last element of ES6 Map without iterations?

containers,ecmascript-6
How to get a last element of ES6 Map/Set without iterations(forEach or for of) pass through a full length of the container?

What is the state of ES6 JavaScript, is it approved, what other steps are required?

javascript,ecmascript-6
Regarding the approval process of the next version of Ecmascript - where are we at in the implementation process - and how does anyone know? Is there somewhere that EcmaScript progress is tracked? Is there a W3C link that will give an announcement or is this something that will happen?...

Include paths for imports in babel using webpack

ecmascript-6,webpack,babeljs
Given a directory structure such as: project ├───common │ └───js └───src └───js is there any way to add import paths to webpack so that a script inside src/js can resolve code inside common/js if it cannot find anything else locally? Something like the code below would include common/js/CommonClass.js: import CommonClass...

ES6 Object Literal Property Value Shorthand

ecmascript-6
Using the new shorthand feature in ES6 for object literals, is it possible to use obj.id and have it parse as id: obj.id? Wondering if I've missed something in the new spec... create(obj) { this.connection.send({ obj.id }); this.add(obj); }, ...

“Variable 'X' can be made constant”, what does 'constant' mean?

typescript,resharper,ecmascript-6
VStudio or ReSharper is giving me the suggestion below: What does constant mean in this scenario? If it's a constant in the current method scope, what's the purpose? Methods tend to be small and therefore it shouldn't give any advantage compared to be a regular var? Please enligten me...

ES2015 Babel String Interpolation not working with apostrophe (but does with double quotes)

javascript,ecmascript-6,babeljs
I am using babel / grunt to learn some ES2015. According to this post there is no real difference in Javascript between single and double quotes. i.e. 'test' and "test". When trying string interpolation though, it seems there is an issue with babeljs (or more likely - me). What is...

Angular 1.4 + ngNewRouter + ES6 : Cannot read property '$routeConfig' of undefined

angularjs,ecmascript-6,angular-new-router
I am currently trying to throw together a basic working example of an Angular 1.4 app written with both the new router as well as ECMAScript 6. I have been fiddling with this code non stop and I don't understand why I am getting the error that is being thrown:...

Dynamic key in immutability update helper for array

javascript,reactjs,ecmascript-6
https://facebook.github.io/react/docs/update.html I have an update function that receives an index along with the event so as to alter the value for that specific item in the array. How do I get index to be evaluated instead of treated as a set key in this scenario? Is it even possible? updateValue:...

Compile a directory tree of separate apps (one entry point each), using CommonJS modules and ES6 modules

build,couchdb,ecmascript-6,commonjs
I am writing a Couch app. The output of the build process must be a directory tree of self contained JS files, like so: dist ├── _attachments │ ├── logo.jpg │ └── splash.jpg ├── lists │ └── sitemap.js ├── shows │   ├── article.js │ ├── home.js │ └── dashboard.js ├──...

ES6 Promise blocks page

javascript,ecmascript-6,es6-promise
Given the following test code: var p = new Promise(function(resolve, reject) { for(var i=0;i<10000000;++i) for(var y=i;y<10000000;++y) z = i + y; resolve(); }); p.then(function(){alert("resolved");}); This code should run asynchronously, but it blocks all interaction with the page. Why? This was tested in Chrome 44, according to this table Promises should...

ES6 read-only enums that can map value to name

enums,ecmascript-6
I would like to define an enum-like structure in JS, but have two requirements: The values be read-only, i.e. no users can assign to them. The values (0, 1, 2, ...) can be mapped back into the names (as with Java's name method) The methods I know to create enums...

`Map` returns empty object with BabelJS

node.js,ecmascript-6,babeljs
I'm trying to run following code with BabelJs: var m = new Map(); m.set('a', 'b'); m.set('b', 1); m.set('c', { a: 12 }); console.log(m); console.log(typeof m); But I get an empty object from babel-node as a result: {} object What's the problem? ...

DOM based XSS is possible in this example?

javascript,security,xss,ecmascript-6
I've been reading a bundle of documents about DOM based XSS but I still can't figure it out. Let's take a look at my example. var html = ` <a class="url" href="${untrustedURL}"> <img src="${untrustedSource}"> </a> <span class="name" data-value="${untrustedValue}">${untrustedText}</span> `; document.querySelector('#user').innerHTML = html; How can an attacker exploit the vulnerabilities of...

How to test if browser supports js ES6 Class? [duplicate]

javascript,class,ecmascript-6,browser-support
This question already has an answer here: Javascript ES6 cross-browser detection 2 answers My js classes works fine in Chrome, but when I test in IE for example, the script fails as expected, giving an ugly syntax error. Is there someway to test if the clients browser can handle...

Inheriting defaultProps from superclass in React

inheritance,reactjs,ecmascript-6
I think some props, like "theme", are so universal among components that it makes sense to extract their handling (to a superclass). Then it follows that their default value also belongs there. However, using React this doesn't seem possible: class Base extends React.Component { bgColor() { switch (this.props.theme) { case...

How will Javascript Map object improve our coding?

javascript,ecmascript-6
If we can make key/value pairs with javascript Objects, then what is suppose to be the use for the ES6 new Map() object? When should I use one and when the other? Is Map limited to values or can it contain functions as well?...

Extend a String class in es6

javascript,string,ecmascript-6
I can write the following in es5: String.prototype.something=function(){ return this.split(' ').join(''); }; How do I do the same thing in es6 using the new features ? PS : I know that this is also a valid es6. I wan't to know whether there's any other way of implementing such functions...

ES6: call class constructor without new keyword

javascript,ecmascript-6
Given a simple class class Foo { constructor(x) { if (!(this instanceof Foo)) return new Foo(x); this.x = x; } hello() { return `hello ${this.x}`; } } Is it possible to call the class constructor without the new keyword? Usage should allow (new Foo("world")).hello(); // "hello world" Or Foo("world").hello(); //...

ECMAScript 6: what is WeakSet for?

javascript,ecmascript-6,traceur
The WeakSet is supposed to store elements by weak reference. That is, if an object is not referenced by anything else, it should be cleaned from the WeakSet. I have written the following test: var weakset = new WeakSet(), numbers = [1, 2, 3]; weakset.add(numbers); weakset.add({name: "Charlie"}); console.log(weakset); numbers =...

ES6 module scope

javascript,module,ecmascript-6
I have the code: // lib.js var a = "a"; export var b = "b"; // main.js console.log(a); // "a" variable is not available in a global scope import {b} from "lib"; console.log(a); // is "a" variable available in a global scope or only in a module scope? Can I...

React.js communicate with state object from outside component

javascript,reactjs,ecmascript-6
Using the React DnD lib: const itemDropTarget = { acceptDrop(component, item) { window.alert('You dropped ' + item.name + '!'); } }; const Container = React.createClass({ mixins: [DragDropMixin], getInitialState() { return { items: [] }; }, statics: { configureDragDrop(register) { register(ItemTypes.ITEM, { dropTarget: itemDropTarget }); } } }); Wondering how I...

Why should I use ES6 classes? [closed]

javascript,ecmascript-6
I have many question about ES6 classes. Since i understand how to use function and WebComponent, React & so. I didn't see many benefit using it. I wonder what's the benefit of using classes. I read that public/private/static will be part of ES7. So i see no point using it...

ServiceWorker and Push Notification Payload

node.js,android-gcm,ecmascript-6,service-worker,chrome-gcm
Community: ServiceWorker is a great advance technology in terms of cache managment, but I have some questions associated with other operations such as: Push Notification: I made a GCM integration (Google Clud Message) and NodeJS, following this article, the problem is that when GCM sends the information to the client...

Is there any way to modify a Set data structure in iteration (ECMAScript 6)?

ecmascript-6
The Set object in ES6 has a forEach method, just like Array object does. Is there any way to modify the values when iterating over the Set object using the forEach method? For example: // Array object in ES5 can be modified in iteration var array = [1, 2, 3];...

How to circumvent the ES6 Class scoping issue with 'this' key word [duplicate]

javascript,socket.io,this,ecmascript-6
This question already has an answer here: How to access the correct `this` / context inside a callback? 4 answers How do I write a named arrow function in ES6? 1 answer For example in the Class constructor: Socket.on('user:join', onUserJoin); 'onUserJoin' is declared as a method of the class...

MongoDB Object key with ES6 template string

javascript,mongodb,ecmascript-6
I'm trying to update an array in my collection with this: var str = "list.0.arr"; db.collection('connect').update({_id: id}, {$push: { `${str}`: item}}); This exact string works just fine if I do it like this: db.collection('connect').update({_id: id}, {$push: { "list.0.arr": item}}); This is to show that it works, but It's throwing an...

Use requirejs modules as es6 module

javascript,requirejs,ecmascript-6,commonjs,es6-module-loader
I'm trying to migrate my project to ES6 modules, but I met an issue. I have 3rd party script that use modules with help of requirejs. Let name it 3rdParty.js. It was obtained via bower, so there is no ability and wish to update it. Is there any way to...

Can derived classes have static get methods?

ecmascript-6,ecmascript-harmony
Update 2, added Gist: Question: Can derived classes have static get methods? 3 files here, with attempted use of static get method in a derived class. It works correctly when accessed inside the class' .es6 file, but doesn't when imported for tests. I'm just getting my head around ES6 class...

Mixins for ES6 classes, transpiled with babel

javascript,mixins,ecmascript-6
According to various sources (2ality, esdiscuss) one should be able to add mixins to classes: EDIT discovered that class methods are not enumerable so that cannot work. Edited the code below, but still no joy class CartoonCharacter { constructor(author) { this.author = author; } drawnBy() { console.log("drawn by", this.author); }...

ES6 Iterate over class methods

javascript,ecmascript-6
Given this class; how would i iterate over the methods that it includes? class Animal { constructor(type){ this.animalType = type; } getAnimalType(){ console.log('this.animalType: ', this.animalType ); } } let cat = window.cat = new Animal('cat') What I have tried is the following with no success: for (var each in Object.getPrototypeOf(cat)...

Is there any reason I wouldn't use “let”?

javascript,const,var,ecmascript-6,let
Now that we can write ES6 and deploy it to browsers (using Traceur or 6to5 to support legacy user agents), is there any reason why we wouldn't use let or const as our default keywords for variable declaration? Is var dead? And if it is, can I configure my linting...

Using a rest parameter before the last parameter in function definition

javascript,ecmascript-6
My problem is best explained with a simple code example: function doThing(a, ...b, c) { console.log(a, b, c) } doThing(1,2,3,4); // Expect "1 [2,3] 4" This instead gives a syntax error Unexpected token, pointing to the comma after the b in the function definition. Is it not possible to put...

Implicit Accessors in JavaScript?

javascript,ecmascript-6,accessor,ecmascript-harmony
In ColdFusion (a server-side language), it's possible to have CF generate any getters and setters in a class for you, like so: component output="false" accessors="true" { property string title; public any function init() output = false { setTitle(""); return this; } } Here, I never write the setTitle() setter, it's...

“Import” ES6 for Node

javascript,node.js,ecmascript-6
I want to use import from ES6 rather than require from common.js in Node. For some reason I thought import would work by default in Node. But looks like it does not. Is there some npm package i need to install for that to work?

Extended Errors do not have message or stack trace

javascript,ecmascript-6,babeljs
When running this snippet through BabelJS: class FooError extends Error { constructor(message) { super(message); } } let error = new FooError('foo'); console.log(error, error.message, error.stack); it outputs {} which is not what I expect. Running error = new Error('foo'); console.log(error, error.message, error.stack); produces {} foo Error: foo at eval (eval at...

Prototype chains in ECMAScript 6

javascript,subclass,ecmascript-6,ecmascript-harmony
I recently came across this great post by Dr. Axel Rauschmayer: http://www.2ality.com/2015/02/es6-classes-final.html The following snippet roughly describes how ECMAScript 6 prototype chains work from an ECMAScript 5 point of view (section 4.2 of the original post): // ECMAScript 6 class Point { constructor(x, y) { this.x = x; this.y =...

React components as plain JS objects?

javascript,class,reactjs,javascript-objects,ecmascript-6
Does anybody has experience in working with React components as plain JS objects instead of annoying ES6 classes and deprecated .createClass method. Maybe you have some examples of factory functions or similar to share? Thanks!...

Create a subset object, consisting of only some of the properties of an existing object

javascript,ecmascript-6
This is best explained by example. The following works in es6 to create an object consisting of some of the keys of an existing object: var o = {a:1, b: 2, c: 3} var {a, c} = o var subsetObj = {a, c} // will be: {a:1, c:3} There are...

ES6 - Convert from 'require' to 'import'

ecmascript-6
If the alternative to: var Foo = require('foo'); is: import Foo from 'foo'; What is the alternative to: var Bar = require('foo').batz Could it be: import {batz} from 'foo' ? ...

What's the purpose of allowing duplicate property names?

javascript,standards,ecmascript-6
I'm reading the MDN javascript reference, accordingly the following code no longer returns false: function haveES6DuplicatePropertySemantics(){ "use strict"; try { ({ prop: 1, prop: 2 }); // No error thrown, duplicate property names allowed in strict mode return true; } catch (e) { // Error thrown, duplicates prohibited in strict...

ES6 module import is not defined during debugger

ecmascript-6,webpack,javascript-debugger,babeljs
While playing around with Babel and Webpack I stumbled into some really weird behavior today. I threw a debugger in my main.js to see if I was importing correctly, but Chrome's console kept yelling that the module I was trying to import was not defined. I try console logging the...

performance between object.property and map.get(object)

javascript,performance,v8,ecmascript-6
In ECMAScript 6, I have two way to define a dictionary: Traditional method (with dictionary = Object.create(null)): set property: dictionary.key = value or dictionary[key] = value get property: dictionary.key or dictionary[key] Using Map (with dictionary = new Map()): set a reference: dictionary.set(key, value) get a reference: dictionary.get(key) In V8, are...

IntelliJ/Webstorm not finding import reference

javascript,intellij-idea,phpstorm,webstorm,ecmascript-6
I have the following project structure: root src scripts main.js foo.js Inside of my main.js file, I'm importing foo.js like so: import 'src/scripts/foo.js' When I click on the import statement above and go to Navigate -> Declaration I get a super helpful message that says Cannot find declaration to go....

How to use aurelia-validate with a object properties to validate?

decorator,ecmascript-6,aurelia,aurelia-validation
I'm using aurelia-validate and my validation works fine if I use variables, but I need it to validate properties of an object rather than a variable: Here's what works: import {Validation} from 'aurelia-validation'; import {ensure} from 'aurelia-validation'; import {ItemService} from './service'; export class EditItem { static inject() { return [Validation,...

ES6 shorthand object key checking

javascript,ecmascript-6,babeljs
Curious to know if there's any part of ES6 that makes these kind of checks a little more concise: componentWillReceiveProps(nextProps) { if(nextProps && nextProps.filterObj && nextProps.filterObj.area){ // go ahead } } ...

sum of uint8array javascript

javascript,ecmascript-6,typed-arrays
I'm trying to sum and then average a stream of data, some code here. var getAverage = function(dataArray){ var total, sample = dataArray.length, eArray = Array.prototype.slice.call(dataArray); for (var i = 0; i< sample; i++) { total+= eArray[i]; } return total; } var output = function(){ //source data var dataArray =...

Symbol.for(string) in ECMAScript 6

javascript,symbols,ecmascript-6
It took me a while but I finally figured out what the purpose of symbols in ECMAScript 6 is: avoiding name collision when attaching properties to shared objects - HTML elements e.g. (In case you're stuck on the same question, I recommend this article.) But then I stumbled upon Symbol.for()....

Babelify ParseError on import module from node_modules

javascript,node.js,browserify,ecmascript-6,babeljs
I'm using ES6 with Babelify and CommonJS module formatter. And I using ES6 style module features with node's module system. So, I'm going to put in all my own modules in node_modules/libs folder. test.js in [ node_modules/libs ] export default function() { console.log('Hello'); }; main.js (will compile to bundle.js) import...

Unit testing with Karma on an Angular 1.3/JSPM/Babel project

angularjs,karma-runner,ecmascript-6,jspm
So I'm setting up an angular 1.3 es6 project using jspm and babel. Im using es6's import/export feature. I have karma and karma-jspm installed and can run basic tests without an issue. When I try to import one of my modules into a test to test it, I get an...

How does `this` work in default parameters?

javascript,ecmascript-6
So... ES6¹ (which happens to be standardized a few hours ago) brings default parameters for functions similar to those in PHP, Python etc. I can do stuff like: function foo (bar = 'dum') { return bar; } foo(1); // 1 foo(); // 'dum' foo(undefined); // 'dum' MDN says that the...

why obj={x,y} works in Chrome?

javascript,ecmascript-6
var obj = { type: 'data', x, y, data: []} Obviously this was my typo, {x,y} should have been {x:x, y:y}. But it does what I want, in Chrome, field x gets the value of a local variable x. But why does it work?...

How to map JSON data to a class

javascript,ecmascript-6,babeljs
I created a ES6 class by Babel and I want to map JSON data which is gotten from a server to the ES6 class. Is there anything common way to do that? User.js export default class User { constructor() { this.firstName; this.lastName; this.sex; } } app.js import User from "./classes/User";...

Injected dependencies not accessible in class methods for AngularJS

javascript,angularjs,dependency-injection,ecmascript-6
I'm using ES6 classes for Angular controllers and I'm running into a slight annoyance with dependency injection. Take this controller, for example (obviously not a real class). class PersonController { constructor(MyDependency) { MyDependency.test(); // this works } sendEvent() { MyDependency.test(); // MyDependency is undefined } } PersonController.$inject = ['MyDependency']; export...

What's the sytax for importing all Math functions in ECMA 6?

ecmascript-6
I have something like this: import * as math from "lib/math"; alert("2π = " + math.sum(math.pi, math.pi)); And I know this is possible: import {sum, pi} from "lib/math"; alert("2π = " + sum(pi, pi)); But is there a way to import all Math functions in my namespace at once? Something...

Using Node's `response.end` method with promise

javascript,node.js,http,promise,ecmascript-6
Suppose I have a basic HTTP server that responds to everything with "foo": import http from 'http' http.createServer((request, response) => Promise.resolve('foo\n').then(s => response.end(s)) ).listen(8888) This works, but when I change the .then line to a shorter version: Promise.resolve('foo\n').then(response.end) It doesn't end the response. I must be missing something very dumb...

ES6 classes : what about instrospection?

javascript,class,ecmascript-6,introspection
In ES5, I could check the existence of a "class" (constructor function) on the window object: if (window.MyClass) { ... // do something } In ES6, according to this article, globally-declared classes are globals, but not properties of the global object (window, on browsers): But there are now also global...

Promise.allSettled in babel ES6 implementation

javascript,node.js,ecmascript-6,babel,es6-promise
I'm using babel to transpile my [email protected] code and I'm stuck with promises. I need allSettled-type functionality that I could use in q and bluebird or angular.$q for example. On babel's core-js Promise, there is no allSettled method. Currently I'm using q.allSettled as a workaround: import { allSettled } from...

Is ES6 module loader part of standard?

javascript,ecmascript-6
I want to clarify this issue. Some articles on the net says that ES6 module loader is part of the ES6 standard. But I cannot find proves in the ES6 draft. But if ES6 module loader isn't part of the standard, how it's supposed to conditionally/dynamically load dependencies?...