JavaScript Extending Class

Updated below for ES6 March 2013 and ES5 This MDN document describes extending classes well: https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript In particular, here is now they handle it: // define the Person Class function Person() {} Person.prototype.walk = function(){ alert (‘I am walking!’); }; Person.prototype.sayHello = function(){ alert (‘hello’); }; // define the Student class function Student() { // … Read more

How to run Node.js app with ES6 features enabled?

Add the babel-cli and babel-preset-es2015 (aka ES6) dependencies to your app’s package.json file and define a start script: { “dependencies”: { “babel-cli”: “^6.0.0”, “babel-preset-es2015”: “^6.0.0” }, “scripts”: { “start”: “babel-node –presets es2015 app.js” } } Then you can simply execute the following command to run your app: npm start If you ever decide to stop … Read more

Spread Syntax vs Rest Parameter in ES2015 / ES6

When using spread, you are expanding a single variable into more: var abc = [‘a’, ‘b’, ‘c’]; var def = [‘d’, ‘e’, ‘f’]; var alpha = [ …abc, …def ]; console.log(alpha)// alpha == [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]; When using rest arguments, you are collapsing all remaining arguments of a function into one array: … Read more

Array.from() vs spread syntax

Spread element (it’s not an operator) works only with objects that are iterable (i.e. implement the @@iterator method). Array.from() works also on array-like objects (i.e. objects that have the length property and indexed elements) which are not iterable. See this example: const arrayLikeObject = { 0: ‘a’, 1: ‘b’, length: 2 }; // This logs … Read more

New es6 syntax for importing commonjs / amd modules i.e. `import foo = require(‘foo’)`

The correct way is to continue using the old import syntax. The new import syntax is for ES modules only, the old import syntax is for pre-ES6 modules. The two are distinct, intentionally so. import * as foo from ‘foo’ imports all the properties of the module ‘foo’, it does not import the default value … Read more

How to return anonymous object from one liner arrow function in javascript? [duplicate]

Put parens around the object initializer: data.map((d) => ({id: d.id, selected: bool}) ); Parentheses have no effect on the value of the expression inside them, but they do have the syntactic effect of eliminating the ambiguity of the first token of the contained expression. Without the parentheses, the JavaScript parser has to decide whether the … Read more