background preloader

JavaScript Promises: There and back again

Ladies and gentlemen, prepare yourself for a pivotal moment in the history of web development… [Drumroll begins] Promises have arrived natively in JavaScript! [Fireworks explode, glittery paper rains from above, the crowd goes wild] At this point you fall into one of these categories: People are cheering around you, but you're not sure what all the fuss is about. What's all the fuss about? JavaScript is single threaded, meaning that two bits of script cannot run at the same time, they have to run one after another. As a human being, you're multithreaded. You've probably used events and callbacks to get around this. var img1 = document.querySelector('.img-1'); img1.addEventListener('load', function() { // woo yey image loaded}); img1.addEventListener('error', function() { // argh everything's broken}); This isn't sneezy at all. This doesn't catch images that error'd before we got a chance to listen for them, unfortunately the DOM doesn't give us a way to do that. Promise terminology fulfilled Related:  ES6/ES2015

ECMAScript 6: New Features: Overview and Comparison Deploying ECMAScript 6 This blog post describes the options you have for deploying ECMAScript 6 in current JavaScript environments. It is selective w.r.t. the amount of tools it covers. If you want a comprehensive list of tools, I suggest you look at Addy Osmani’s “ECMAScript 6 Tools”. Consult the blog post “Using ECMAScript 6 today” for an overview of ES6 features. Using ECMAScript 6 today What options do you have for using ECMAScript 6 today? ECMAScript 6 features are continually appearing in engines. Especially if you take support for legacy engines into consideration, compiling ES6 to ES5 will be the only viable option for using ES6 for quite a while. The nice thing about ES6 is that it is a superset of ES5, which means that all of your ES5 code bases are already valid ES6. Using ECMAScript 6 natively As soon as the first engine fully supports ES6 and until all non-ES6 engines go away, a hybrid approach could be used for client-side apps: Transpilation tools Choosing a transpiler Static transpilation ES6 REPLs

Hilbert's Grand JavaScript School (2015 Edition) (This material originally appeared, using ECMAScript-5 semantics, in 2013.) Dr. Hilbert “Bertie” David grows tired of blogging about JavaScript, and decides to cash in on the seemingly inexhaustible supply of impressionable young minds seeking to “Learn JavaScript in Five Days.” He opens his Grand JavaScript School on the shores of the Andaman Sea in Thailand, and with some clever engineering, he is able to install a countably infinite number of seats in his lecture hall. day one Well, an infinite number of students show up on the first day. Bertie quickly whips out a JavaScript IDE he has devised, and he writes himself a generator. function* Numbers (from = 0) { let number = from; while (true) yield number++;}; const seats = Numbers(); for (let seat of seats) { console.log(seat);} //=> 0 1 2 3 ... He simply calls out the numbers as they are printed, and the students file into the auditorium in an orderly fashion, filling it completely. day two Out comes the IDE and the bullhorn. day three

De Stijl: How necessary are var, let, and const? Disclaimer: JavaScript the language has some complicated edge cases, and as such, the following essay has some hand-wavey bits and some bits that are usually correct but wrong for certain edge cases. If it helps any, pretend that nearly every statement has a footnote reading, “for most cases in practice, however ______.” ECMAScript-2015 gives us three different variable declaration statements: var, let, and const. We already had var. One way to answer that question is to perform a thought experiment: Take a function using one of these features, and convert it to an equivalent function that doesn’t use the feature. is var necessary? Let’s try this with var. Variables declared with var have exactly the same scope as function arguments. So: function callFirst (fn, larg) { return function () { var args = Array.prototype.slice.call(arguments, 0); return fn.apply(this, [larg].concat(args)) }} Would become: We can manually hoist any var that doesn’t appear at the top of the function, so: And then:

ES6 In Depth – Symbols ES6 In Depth is a series on new features being added to the JavaScript programming language in the 6th Edition of the ECMAScript standard, ES6 for short. Note: There is now a Vietnamese translation of this post, created by Julia Duong of the Coupofy team. What are ES6 symbols? Symbols are not logos. They’re not little pictures you can use in your code. let 😻 = 😺 × 😍; They’re not a literary device that stands for something else. They’re definitely not the same thing as cymbals. (It is not a good idea to use cymbals in programming. So, what are symbols? The seventh type Since JavaScript was first standardized in 1997, there have been six types . UndefinedNullBooleanNumberStringObject Each type is a set of values. The set of Object values, however, is open-ended. ES6 symbols are values, but they’re not strings. Let’s talk about a scenario where they might come in handy. One simple little boolean How can you solve this? One way is to use CSS APIs to ask the browser if the element is moving. Hmm.

Metaprogramming in ES6: Symbols and why they're awesome You've heard of ES6 right? It's the new version of JavaScript that is awesome in so many ways. I frequently wax lyrical about all of the amazing new features I keep discovering with ES6, much to the chagrin of my colleagues (consuming someone's lunch break talking about ES6 Modules seems to be not to everyone's liking). A set of great new features for ES6 comes in the form of a slew of new metaprogramming tools, which provide low level hooks into code mechanics. Not much has been written on them, so I thought I'd do a teensy weensy 3 part post on them (sidebar; because I'm so lazy and this post has been sat in my drafts folder - 90% done - for three months, a bit more has been written about them since I said that): Part 1: Symbols (this post) Part 2: Reflect Part 3: Proxies (coming soonish) First, let's take a quick detour and discover the wonderful world of Metaprogramming. class BoringClass end class CoolClass def ==(other_object) other_object.is_a? So how does each one work? 1. 3.

ES6 Feature Performance - incaseofstairs Update: The results below are a snapshot from when this post was written. kpdecker.github.io/six-speed/ has the most recent results. With ES6 features landing quickly in native browsers and readily available for use through Babel and Traceur, it seemed like it was time to look not just at support, but also the performance impact of using these features under the current implementations. While there is great promise for the future, the picture of ES6 feature performance today is very muddled and depends on the specific feature being used. Some such as bindings and simple arrow/destructuring are ready for use today, others such as generators and tagged template strings might require analysis before using. The standard warnings of premature optimization and recommendations to profile your own code apply to the comments here. These tests are very micro in their scope and might not be representative of your particular use case. Results Arrow Function Issues: Firefox Native Implementation Classes

ES2015 et ES2016 dans votre navigateur Il est bien entendu que tout ce qui va suivre ne doit pas se retrouver en production (après vous faites comme vous voulez). Préparation de votre environnement Tout d'abord vous avez vesoin de JSPM qui est un gestionnaire de package s'appuyant sur la gestion des modules façon ES6 (ES2015). Donc, dans un 1er temps, installez JSPM: npm install jspm -g (précédé de sudo pour les Mac users). jspm init JSPM va vous poser une série de questions: Package.json file does not exist, create it? Normalement, répondez avec les valeurs par défaut. A la question Enter server baseURL (public folder path) [./]: vous pouvez répondre par exemple public si votre webapp est dans un sous répertoire public, sinon laissez tel quel. Vous aurez besoin d'un serveur http (j'utilise http-server: Création de notre page index.html <! La ligne System.import("main"); signifie que nous allons charger main.js. Création de main.js et message.js import Message from '. <!

JavaScript ES6+: var, let, or const? — JavaScript Scene Perhaps the most important thing you can learn to be a better coder is to keep things simple. In the context of identifiers, that means that a single identifier should only be used to represent a single concept. Sometimes it’s tempting to create an identifier to represent some data and then use that identifier as a temporary place to store values in transition from one representation to another. For instance, you may be after a query string parameter value, and start by storing an entire URL, then just the query string, then the value. It’s easier to understand if you use one identifier for the URL, a different one for the query string, and finally, an identifier to store the parameter value you were after. This is why I favor `const` over `let` in ES6. If I don’t need to reassign, `const` is my default choice over `let` because I want the usage to be as clear as possible in the code. I use `let` when I need to reassign a variable. I don’t use `var` in ES6. Warning:

kpdecker.github Run on 2016-09-09 using babel 6.14.0, babel-runtime 6.11.6, and traceur 0.0.108. For each of the ES6 features in question, a ES5 implementation of that functionality was written along with a ES6 version. It should be noted that the functionality is frequently the same, but in some cases the "common" vs. "correct" version was written, i.e. using x[key] = value vs. defineProperty which is faster but can be hit but a particular nasty edge case for those who deem it fun to extend Object.prototype. Babel, in both loose+runtime and runtime mode, and Traceur were then used to compile the ES6 version to a ES5 compliant version, utilizing the runtime over polyfill to maintain test isolation and avoid native implementations where possible. All of these test instances were then benchmarked in the given JavaScript engine using Benchmark.js and then the operations per second compared to the ES5 implementation.

Related: