Convert a string to a template string

In my project I’ve created something like this with ES6: String.prototype.interpolate = function(params) { const names = Object.keys(params); const vals = Object.values(params); return new Function(…names, `return \`${this}\`;`)(…vals); } const template=”Example text: ${text}”; const result = template.interpolate({ text: ‘Foo Boo’ }); console.log(result);

Call static methods from regular ES6 class methods

Both ways are viable, but they do different things when it comes to inheritance with an overridden static method. Choose the one whose behavior you expect: class Super { static whoami() { return “Super”; } lognameA() { console.log(Super.whoami()); } lognameB() { console.log(this.constructor.whoami()); } } class Sub extends Super { static whoami() { return “Sub”; } … Read more

How to load external scripts dynamically in Angular?

You can use following technique to dynamically load JS scripts and libraries on demand in your Angular project. script.store.ts will contain the path of the script either locally or on a remote server and a name that will be used to load the script dynamically interface Scripts { name: string; src: string; } export const … Read more

Null-safe property access (and conditional assignment) in ES6/2015

Update (2022-01-13): Seems people are still finding this, here’s the current story: Optional Chaining is in the specification now (ES2020) and supported by all modern browsers, more in the archived proposal: https://github.com/tc39/proposal-optional-chaining babel-preset-env: If you need to support older environments that don’t have it, this is probably what you want https://babeljs.io/docs/en/babel-preset-env Babel v7 Plugin: https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining … Read more

Not recommended to use “use strict” in ES6?

ES6 modules are always in strict mode. To quote the relevant part of the spec: 10.2.1 Strict Mode Code An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations: Global code is strict mode code if it … Read more

How to convert a plain object into an ES6 Map?

Yes, the Map constructor takes an array of key-value pairs. Object.entries is a new Object static method available in ES2017 (19.1.2.5). const map = new Map(Object.entries({foo: ‘bar’})); map.get(‘foo’); // ‘bar’ It’s currently implemented in Firefox 46+ and Edge 14+ and newer versions of Chrome If you need to support older environments and transpilation is not … Read more