Je vais transcrire mon thread sur JavaScript et un film d'horreur de Mastodon sur Twitter.
Axios is a simple promise based HTTP client for the browser and node.js. Axios provides a simple to use library in a small package with a very extensible interface.
JavaScript library for reorderable drag-and-drop lists
RE:DOM is a tiny (2 KB) DOM library, which adds useful helpers to create DOM elements and keeping them in sync with the data.
The aerogel-weight jQuery-compatible JavaScript library
Lightweight and intuitive javascript library to speed up your web development
You can simply save and restore the entire events object:
var events=$._data(elem, 'events'); // save events
$._data(elem, 'events', {}); // cancel all events
// any code here will not fire events
$._data(elem, 'events', events); // restore events
This worked for me but may have unknown side effects ...
Day.js is a minimalist JavaScript library that parses, validates, manipulates, and displays dates and times for modern browsers with a largely Moment.js-compatible API. If you use Moment.js, you already know how to use Day.js.
A free, once–weekly email roundup of JavaScript news and articles.
We help developers, and the companies they work for, stay up-to-date via our variety of publications, across the web, social and by email.
This is an extract from chapter 11 of Ashley Davis’s book Data Wrangling with JavaScript now available on the Manning Early Access Program. I absolutely
It’s been for an hour or two now since I woke up, and I’m still sitting on my bed because my floor is full of bugs. Yes, bugs.. and no, I…
const result = _.map({a: 1, b: 2}, function(value, key) {
return value + key;
});
Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar == foo || foobar == bar) {
//do something
}
And, if you have lots of values, then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set([foo, bar, test1, test2, test3]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.
This lightweight tool helps you get a sense of your application's schema, as well as any outliers to that schema. Particularly useful when you inherit a codebase with data dump and want to quickly learn how the data's structured. Also useful for finding rare keys.
$ mongo test --eval "var collection = 'users'" variety.js
+------------------------------------------------------------------+
| key | types | occurrences | percents |
| ------------------ | ------------ | ----------- | -------- |
| _id | ObjectId | 5 | 100.0 |
| name | String | 5 | 100.0 |
| bio | String | 3 | 60.0 |
| birthday | Date | 2 | 40.0 |
| pets | Array(1),String(1) | 2 | 40.0 |
| someBinData | BinData-old | 1 | 20.0 |
| someWeirdLegacyKey | String | 1 | 20.0 |
+------------------------------------------------------------------+
Aggregation is a very small JavaScript library for Node.js environments, providing just a single function, for use in ECMAScript 5/6 class inheritance based on mixins. It aggregates a base class and one or more mixin classes into an aggregate class, which then is usually subsequently used as the base class for another class.
mics (pronounce: mix) is a library that makes multiple inheritance in Javascript a breeze. Inspired by the excellent blog post “Real” Mixins with Javascript Classes by Justin Fagnani, mics tries to build a minimal library around the concept of using class expressions (factories) as mixins. mics extends the concepts presented in the blog post by making the mixins first-class citizens that can be directly used to instantiate objects and can be mixed in with other mixins instead of just with classes.
The truth is, ternaries are usually much simpler than if statements. People believe the reverse for two reasons:
Before we get into the details, let’s define a ternary expression:
A ternary expression is a conditional expression that evaluates to a value. It consists of a conditional, a truthy clause (the value to produce if the conditional evaluates to a truthy value), and a falsy clause (the value to produce if the conditional evaluates to a falsy value).
Extension for Visual Studio Code - Sublime Text's babel-sublime grammar in VS Code.
A quick overview of new JavaScript features in ES2015, ES2016, ES2017 and beyond.
The (many) reasons why you could not have JS.
Free yourself from the chains of jQuery by embracing and understanding the modern Web API and discovering various directed libraries to help you fill in the gaps.
Preact provides the thinnest possible Virtual DOM abstraction on top of the DOM. The web is a stable platform, it's time we stopped reimplementing it in the name of safety.
Preact is also a first-class citizen of the web platform. It diffs Virtual DOM against the DOM itself, registers real event handlers, and plays nicely with other libraries.
Most UI frameworks are large enough to be the majority of an app's JavaScript size. Preact is different: it's small enough that your code is the largest part of your application.
That means less JavaScript to download, parse and execute - leaving more time for your code, so you can build an experience you define without fighting to keep a framework under control.
Preact is fast, and not just because of its size. It's one of the fastest Virtual DOM libraries out there, thanks to a simple and predictable diff implementation.
It even includes extra performance features like customizable update batching, optional async rendering, DOM recycling, and optimized event handling via Linked State.
Preact's tiny footprint means you can take the powerful Virtual DOM Component paradigm to new places it couldn't otherwise go.
Use Preact to build parts of an app without complex integration. Embed Preact into a widget and apply the same tools and techniques that you would to build a full app.
Lightweight is a lot more fun when you don't have to sacrifice productivity to get there. Preact gets you productive right away. It even has a few bonus features:
Virtual DOM Components make it easy to share reusable things - everything from buttons to data providers. Preact's design means you can seamlessly use thousands of Components available in the React ecosystem.
Adding a simple preact-compat alias to your bundler provides a compatibility layer that enables even the most complex React components to be used in your application.
The built-in js-mode in Emacs does not provide many features for working with js framework beside js editing and syntax highlighting. The tips in this post will help you transform your Emacs into a powerful Javascript IDE.
A practical functional library for JavaScript programmers.
There are already several excellent libraries with a functional flavor. Typically, they are meant to be general-purpose toolkits, suitable for working in multiple paradigms. Ramda has a more focused goal. We wanted a library designed specifically for a functional programming style, one that makes it easy to create functional pipelines, one that never mutates user data.
A free, once–weekly e-mail round-up of JavaScript news and articles.
In JavaScript, functions are first-class objects; that is, functions are of the type Object and they can be used in a first-class manner like any other object (String, Array, Number, etc.) since they are in fact objects themselves. They can be “stored in variables, passed as arguments to functions, created within functions, and returned from functions”.
Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later. This is the essence of using callback functions in JavaScript. In the rest of this article we will learn everything about JavaScript callback functions. Callback functions are probably the most widely used functional programming technique in JavaScript, and you can find them in just about every piece of JavaScript and jQuery code, yet they remain mysterious to many JavaScript developers. The mystery will be no more, by the time you finish reading this article.
Callback functions are derived from a programming paradigm known as functional programming. At a fundamental level, functional programming specifies the use of functions as arguments. Functional programming was—and still is, though to a much lesser extent today—seen as an esoteric technique of specially trained, master programmers.
Fortunately, the techniques of functional programming have been elucidated so that mere mortals like you and me can understand and use them with ease. One of the chief techniques in functional programming happens to be callback functions. As you will read shortly, implementing callback functions is as easy as passing regular variables as arguments. This technique is so simple that I wonder why it is mostly covered in advanced JavaScript topics.
Note the following ways we frequently use callback functions in JavaScript, especially in modern web application development, in libraries, and in frameworks:
Instead of return
, you should use callbacks
as in asynchronous
operations, return
does not wait for the I/O
operation to complete.
JavaScript function hoisting by example
Below are many examples of function hoisting behavior in JavaScript. Ones marked as works successfuly print 'hi!' without errors.
To play around with these examples (recommended) clone them with git and execute them with e.g. node a.js
Notes on hoisting
(I may be using incorrect terms below, please forgive me)
When JS is parsed, a first pass is done over each scope, and function definitions are immediately discovered. An example of a function definition is function foo() {}. When a function is declared like this, with a name, that name becomes available to the entire scope when the code in that scope is executed.
A crude timeline of how JS gets executed:
Parse the scope and detect all function definitions
Execute the code top-to-bottom with all functions found in step 1 available as variables
This behavior is called 'hoisting' because it is almost like the function definitions have been 'hoisted' up to the top of the function.
Assignments are not evaluated until the code is executed. An example of an assignment is var foo = function() {} or var foo = function foo() {}. A function must not be associated with an assignment in order for it to be hoisted (see example L)
Wrapping a function in parenthesis (()) is a quick way to convert a function definition into a function expression, which means it does not get hoisted (similar to assigning the function to a variable). I personally do not use this pattern regularly as I find it overly confusing to newbies etc, but I have included it because it is widely used in e.g. jQuery plugins.
I use hoisting as a code organization tool, for example here I rely on hoisting to make parseStream() available on line 20, even though it is defined on line 41, which I think makes that file more readable as I can put the 'meat' of the function at the top.
Callbacks are just the name of a convention for using JavaScript functions. There isn't a special thing called a 'callback' in the JavaScript language, it's just a convention. Instead of immediately returning some result like most functions, functions that use callbacks take some time to produce a result. The word 'asynchronous', aka 'async' just means 'takes some time' or 'happens in the future, not right now'. Usually callbacks are only used when doing I/O, e.g. downloading things, reading files, talking to databases, etc.
The most important aspect of avoiding callback hell is moving functions out of the way so that the programs flow can be more easily understood without newcomers having to wade through all the detail of the functions to get to the meat of what the program is trying to do.
You can start by moving the functions to the bottom of the file, then graduate to moving them into another file that you load in using a relative require like require('./photo-helpers.js') and then finally move them into a standalone module like require('image-resize').
Here are some rules of thumb when creating a module:
Try reading my longer introduction to callbacks, or try out some of the nodeschool tutorials.
Also check out the browserify-handbook for examples of writing modular code.
What about promises/generators/ES6 etc?
Before looking at more advanced solutions, remember that callbacks are a fundamental part of JavaScript (since they are just functions) and you should learn how to read and write them before moving on to more advanced language features, since they all depend on an understanding of callbacks. If you can't yet write maintainable callback code, keep working at it!
If you really want your async code to read top-to-bottom, there are some fancy things you can try. Note that these may introduce performance and/or cross platform runtime compatibility issues, so make sure to do your research.
Promises are a way to write async code that still appears as though it is executing in a top-down way, and handles more types of errors due to encouraged use of try/catch style error handling.
Generators let you 'pause' individual functions without pausing the state of the whole program, which at the cost of slightly more complex to understand code lets your async code appear to execute in a top-down fashion. Check out watt for an example of this approach.
Async functions are a proposed ES7 feature that will further wrap generators and promises in a higher level syntax. Check them out if that sounds interesting to you.
Personally I use callbacks for 90% of the async code I write and when things get complicated I bring in something like run-parallel or run-series. I don't think callbacks vs promises vs whatever else really make a difference for me, the biggest impact comes from keeping code simple, not nested and split up into small modules.
Regardless of the method you choose, always handle every error and keep your code simple.
Remember, only you can prevent callback hell and forest fires
You can find the source for this on github.
Browserify lets you require('modules') in the browser by bundling up all of your dependencies.
jQuery and its cousins are great, and by all means use them if it makes it easier to develop your application.
If you're developing a library on the other hand, please take a moment to consider if you actually need jQuery as a dependency. Maybe you can include a few lines of utility code, and forgo the requirement. If you're only targeting more modern browsers, you might not need anything more than what the browser ships with.
At the very least, make sure you know what jQuery is doing for you, and what it's not. Some developers believe that jQuery is protecting us from a great demon of browser incompatibility when, in truth, post-IE8, browsers are pretty easy to deal with on their own.
jQuery and its cousins are great, and by all means use them if it makes it easier to develop your application.
If you're developing a library on the other hand, please take a moment to consider if you actually need jQuery as a dependency. Maybe you can include a few lines of utility code, and forgo the requirement. If you're only targeting more modern browsers, you might not need anything more than what the browser ships with.
At the very least, make sure you know what jQuery is doing for you, and what it's not. Some developers believe that jQuery is protecting us from a great demon of browser incompatibility when, in truth, post-IE8, browsers are pretty easy to deal with on their own.
No JavaScript frameworks were created during the writing of this article.
The following is inspired by the article “It’s the future” from Circle CI. You can read the original here. This piece is just an opinion, and like any JavaScript framework, it shouldn’t be taken too seriously.