Category Archives: JavaScript

Arrow functions vs. bind()

By Axel Rauschmayer

ES6 arrow functions are often a compelling alternative to Function.prototype.bind().

Extracting methods

If an extracted method is to work as a callback, you must specify a fixed this, otherwise it will be invoked as a function (and this will be undefined or the global object). For example:

    obj.on('anEvent', console.log.bind(console))

An alternative is to use an arrow function:

    obj.on('anEvent', x => console.log(x))

this via parameters

The following code demonstrates a neat trick: For some methods, you don’t need bind() for a callback, because they let you specify the value of this, via an additional parameter. filter() is one such method:

    const as = new Set([1, 2, 3]);
    const bs = new Set([3, 2, 4]);
    const intersection = [...as].filter(bs.has, bs);
        // [2, 3]

However, this code is easier to understand if you use an arrow function:

    const as = new Set([1, 2, 3]);
    const bs = new Set([3, 2, 4]);
    const intersection = [...as].filter(a => bs.has(a));
        // [2, 3]

Partial evaluation

bind() enables you to do partial evaluation, you can create new functions by filling in parameters of an existing function:

    function add(x, y) {
        return x + y;
    }
    const plus1 = add.bind(undefined, 1);

Again, I find an arrow function easier to understand:

    const plus1 = y => add(1, y);

Further reading

Source:: 2ality

Examples of name clashes in JavaScript’s standard library

By Axel Rauschmayer

The main use case for ES6 symbols is that you can use them as property keys that can’t clash with other property keys.

In case you think that name clashes don’t matter, here are three examples of where name clashes caused problems in the evolution of the JavaScript standard library:

In contrast, adding iterability to an object via the property key Symbol.iterator can’t cause problems, because that key doesn’t clash with anything.

These examples demonstrate what it means to be a web language: backward compatibility is crucial, which is why compromises are occasionally necessary when evolving the language. As a side benefit, evolving old JavaScript code bases is simpler, too, because new ECMAScript versions never (well, hardly ever) break them.

Source:: 2ality

ES proposal: Object.getOwnPropertyDescriptors()

By Axel Rauschmayer

Object.getOwnPropertyDescriptors() is an ECMAScript proposal by Jordan Harband and Andrea Giammarchi. It recently advanced to stage 3.

Overview

Object.getOwnPropertyDescriptors(obj) accepts an object obj and returns an object result:

  • For each own (non-inherited) property of obj, it adds a property to result whose key is the same and whose value is the the former property’s descriptor.

Property descriptors describe the attributes of a property (its value, whether it is writable, etc.). For more information, consult Sect. “Property Attributes and Property Descriptors” in “Speaking JavaScript”.

This is an example of using Object.getOwnPropertyDescriptors():

    const obj = {
        [Symbol('foo')]: 123,
        get bar() { return 'abc' },
    };
    console.log(Object.getOwnPropertyDescriptors(obj));
    
    // Output:
    // { [Symbol('foo')]:
    //    { value: 123,
    //      writable: true,
    //      enumerable: true,
    //      configurable: true },
    //   bar:
    //    { get: [Function: bar],
    //      set: undefined,
    //      enumerable: true,
    //      configurable: true } }

This is how you would implement Object.getOwnPropertyDescriptors():

    function getOwnPropertyDescriptors(obj) {
        const result = {};
        for (let key of Reflect.ownKeys(obj)) {
            result[key] = Object.getOwnPropertyDescriptor(obj, key);
        }
        return result;
    }

Use cases for Object.getOwnPropertyDescriptors()

Use case: copying properties into an object

Since ES6, JavaScript already has a tool method for copying properties: Object.assign(). However, this method uses simple get and set operations to copy a property whose key is key:

    const value = source[key]; // get
    target[key] = value; // set

That means that it doesn’t properly copy properties with non-default attributes (getters, setters, non-writable properties, etc.). The following example illustrates this limitation. The object source has a getter whose key is foo:

    const source = {
        set foo(value) {
            console.log(value);
        }
    };
    console.log(Object.getOwnPropertyDescriptor(source, 'foo'));
    // { get: undefined,
    //   set: [Function: foo],
    //   enumerable: true,
    //   configurable: true }

Using Object.assign() to copy property foo to object target fails:

    const target1 = {};
    Object.assign(target1, source);
    console.log(Object.getOwnPropertyDescriptor(target1, 'foo'));
    // { value: undefined,
    //   writable: true,
    //   enumerable: true,
    //   configurable: true }

Fortunately, using Object.getOwnPropertyDescriptors() together with Object.defineProperties() works:

    const target2 = {};
    Object.defineProperties(target2, Object.getOwnPropertyDescriptors(source));
    console.log(Object.getOwnPropertyDescriptor(target2, 'foo'));
    // { get: undefined,
    //   set: [Function: foo],
    //   enumerable: true,
    //   configurable: true }

Use case: cloning objects

Shallow cloning is similar to copying properties, which is why Object.getOwnPropertyDescriptors() is a good choice here, too.

This time, we use Object.create() that has two parameters:

  • The first parameter specifies the prototype of the object it returns.
  • The optional second parameter is a property descriptor collection like the ones returned by Object.getOwnPropertyDescriptors().
    const clone = Object.create(Object.getPrototypeOf(obj),
        Object.getOwnPropertyDescriptors(obj));

Use case: cross-platform object literals with arbitrary prototypes

The syntactically nicest way of using an object literal to create an object with an arbitrary prototype prot is to use the special property __proto__:

    const obj = {
        __proto__: prot,
        foo: 123,
    };

Alas, that feature is only guaranteed to be there in browsers. The common work-around is Object.create() and assignment:

    const obj = Object.create(prot);
    obj.foo = 123;

But you can also use Object.getOwnPropertyDescriptors():

    const obj = Object.create(
        prot,
        Object.getOwnPropertyDescriptors({
            foo: 123,
        })
    );

Another alternative is Object.assign():

    const obj = Object.assign(
        Object.create(prot),
        {
            foo: 123,
        }
    );

Pitfall: copying methods that use super

A method that uses super is firmly connected with its home object (the object it is stored in). There is currently no way to copy or move such a method to a different object.

Further reading

JavaScript design process:

Object.getOwnPropertyDescriptors() and property descriptors:

Source:: 2ality

Feature watch: ECMAScript 2017

By Axel Rauschmayer

Feature watch: ECMAScript 2017

The feature set of ES2016 was recently finalized. This blog post tracks what features may be included in ES2017. I will continually update it.

Proposed ECMAScript features

Recall that every ECMAScript feature proposal goes through stages:

  • Stage 4 means that a feature will probably be in the next release.
  • Stage 3 means that a feature still has a chance of being included in the next release.

The following features are currently at stage 3:

If you are wondering what stages other proposed features are in, consult the readme of the ECMA-262 GitHub repository.

SIMD.JS – SIMD APIs + polyfill (John McCutchan, Peter Jensen, Dan Gohman, Daniel Ehrenberg)

SIMD stands for “single instruction, multiple data”, the ability of a CPU to apply an operand to vectors of values (instead of single values). One popular example of a SIMD instruction set is SSE (Streaming SIMD Extensions), as supported by Intel processors.

This is a short code example, consult the sources below for more information.

    var a = SIMD.float32x4(1.0, 2.0, 3.0, 4.0);
    var b = SIMD.float32x4(5.0, 6.0, 7.0, 8.0);
    var c = SIMD.float32x4.add(a,b);

Further reading:

Source:: 2ality

ES proposal: async functions

By Axel Rauschmayer

Async functions are an ECMAScript proposal by Brian Terlson. It is at stage 3 (candidate).

Before I can explain async functions, I need to explain how Promises and generators can be combined to perform asynchronous operations via synchronous-looking code.

Writing async code via Promises and generators

For functions that compute their one-off results asynchronously, Promises, which are part of ES6, are becoming increasingly popular. One example is the client-side fetch API, which is an alternative to XMLHttpRequest for retrieving files. Using it looks as follows:

    function fetchJson(url) {
        return fetch(url)
        .then(request => request.text())
        .then(text => {
            return JSON.parse(text);
        })
        .catch(error => {
            console.log(`ERROR: ${error.stack}`);
        });
    }
    fetchJson('http://example.com/some_file.json')
    .then(obj => console.log(obj));

co is a library that uses Promises and generators to enable a coding style that looks more synchronous, but works the same as the style used in the previous example:

    const fetchJson = co(function* () {
        try {
            let request = yield fetch(url);
            let text = yield request.text();
            return JSON.parse(text);
        }
        catch (error) {
            console.log(`ERROR: ${error.stack}`);
        }
    });

Every time the callback (a generator function!) yields a Promise to co, the callback gets suspended. Once the Promise is settled, co resumes the callback: if the Promise was fulfilled, yield returns the fulfillment value, if it was rejected, yield throws the rejection error. Additionally, co promisifies the result returned by the callback (similarly to how then() does it).

Async functions

Async functions are basically dedicated syntax for what co does:

    async function fetchJson(url) {
        try {
            let request = await fetch(url);
            let text = await request.text();
            return JSON.parse(text);
        }
        catch (error) {
            console.log(`ERROR: ${error.stack}`);
        }
    }

Internally, async functions work much like generators, but they are not translated to generator functions.

Variants

The following variants of async functions exist:

  • Async function declarations: async function foo() {}
  • Async function expressions: const foo = async function () {};
  • Async method definitions: let obj = { async foo() {} }
  • Async arrow functions: const foo = async () => {};

Further reading

Source:: 2ality

ES2016 feature: exponentiation operator (**)

By Axel Rauschmayer

The exponentiation operator (**) is an ECMAScript proposal by Rick Waldron. It is at stage 4 (finished) and part of ECMAScript 2016.

An infix operator for exponentiation

** is an infix operator for exponentiation:

    x ** y

is produces the same result as

    Math.pow(x, y)

Examples:

    let squared = 3 ** 2; // 9
    
    let num = 3;
    num **= 2;
    console.log(num); // 9

Further reading:

Source:: 2ality

ES2016 feature: Array.prototype.includes

By Axel Rauschmayer

Array.prototype.includes is an ECMAScript proposal by Domenic Denicola and Rick Waldron. It is at stage 4 (finished) and part of ECMAScript 2016.

The Array method includes

The Array method includes has the following signature:

    Array.prototype.includes(value : any) : boolean

It returns true if value is an element of its receiver (this) and false, otherwise:

    > ['a', 'b', 'c'].includes('a')
    true
    > ['a', 'b', 'c'].includes('d')
    false

includes is similar to indexOf – the following two expressions are mostly equivalent:

    arr.includes(x)
    arr.indexOf(x) >= 0

The main difference is that includes() finds NaN, whereas indexOf() doesn’t:

    > [NaN].includes(NaN)
    true
    > [NaN].indexOf(NaN)
    -1

includes does not distinguish between +0 and -0 (which is how almost all of JavaScript works):

    > [-0].includes(+0)
    true

Typed Arrays will also have a method includes():

    let tarr = Uint8Array.of(12, 5, 3);
    console.log(tarr.includes(5)); // true

Frequently asked questions

  • Why is the method called includes and not contains?
    The latter was the initial choice, but that broke code on the web (MooTools adds this method to Array.prototype).

  • Why is the method called includes and not has?
    has is used for keys (Map.prototype.has), includes is used for elements (String.prototype.includes). The elements of a Set can be viewed as being both keys and values, which is why there is a Set.prototype.has (and no includes).

  • The ES6 method String.prototype.includes works with strings, not characters. Isn’t that inconsistent w.r.t. Array.prototype.includes?
    If Array includes worked exactly like string includes, it would accept arrays, not single elements. But the two includes follow the example of indexOf; characters are seen as a special case and strings with arbitrary lengths as the general case.

Further reading

Source:: 2ality

The final feature set of ECMAScript 2016 (ES7)

By Axel Rauschmayer

We always knew that ECMAScript 2016 (ES2016) would be a small release. It turns out that it will be very small. Read on for a list of its features and an explanation why that is not a problem.

The features of ES2016

Any proposals that were at stage 4 on Thursday, 28 January 2016, will be in ES2016 (source: Brian Terlson). That means that ES2016 will contain just two new features (in addition to bug fixes and smaller improvements):

On March 1, a snapshot of the draft of the ECMA-262 specification will be made, to start an editing process that finishes with the ratification of ES2016, probably in June 2016.

The new release process works

ES2016 being so small demonstrates that the new release process works:

  • New features are only included after they are completely ready and after there were at least two implementations that were sufficiently field-tested.
  • Releases happen much more frequently (once a year) and can be more incremental.

If you are disappointed that your favorite stage 3 feature did not make it into ES2016 – don’t worry: With the new release process, it’s more about the stage a proposal is in than what release it is a part of. As soon as a proposal reaches stage 4, it is done and safe to use. You’ll still have to check whether the JavaScript engines that are relevant to you support the feature, but you have to do that with ES6 features, too.

Source:: 2ality

Learn SQL In 20 Minutes

By Danny Markov

learn-sql-20-minutes

Every web developer should know SQL. Although it has been around since the 70s, it is still widely used, and you can’t build a serious application without it. Most full-stack frameworks have libraries for dealing with the SQL complexity – ActiveRecord, Doctrine, Hibernate and more. But often times you need to get your hands dirty and write low-level SQL.

This is why we’ve prepared a short and to-the-point introduction to the basics of SQL. Within the article, you will find our interactive editors for writing and executing your code. Don’t be afraid to experiment with them and try to complete the bonus tasks.

Let’s begin!

1. Create Table

When creating new tables in SQL the CREATE TABLE statement is called. It expects as it’s arguments all the columns we want in the table, as well as the their data types.

Here we are creating a simple table called months. It consists of 3 columns:

  • id – The number of the month in the calendar year (integer).
  • name – Name of the month (string, maximum of 10 characters).
  • days – The number of days in that month (integer).

And this is how the respective SQL looks like:

CREATE TABLE months (id int, name varchar(10), days int);

Also when creating tables, it’s advisable to add a primary key to one of the columns. It will help keep entries unique and will speed up select queries. We won’t be covering them in this lesson but you can read about them here.

2. Insert Rows

Now let’s populate months with a few rows of information. Adding entries to a table is done via the INSERT statement. There are two different ways to use it:

The first way does not specify the column names where the data will be inserted, it only expects the values and leaves it up to the developer to provide all the data in the correct order.

INSERT INTO months VALUES (1,'January',31);

The above is shorter, but there is a major issue – if we add additional columns in the future, the query will break. The preferred way to write this is to include the columns:

INSERT INTO months (id,name,days) VALUES (2,'February',29);

You can try running these commands in the editor below.

Bonus: Write an INSERT statement to add more months to the table.

3. Select

Select queries are our best friend when we want to fetch data from the database. They are used all the time so this lesson is going to spend a lot of time covering them.

The most simple SELECT example would be this query, which will return all the columns and rows from the characters table:

SELECT * FROM "characters"

The asterisk (*) means that we want to grab all of the columns, without excluding anything. Since SQL databases usually consist of more then one table, the FROM keyword is required to specify which table we want to look in.

Sometimes we don’t want all of the columns in a table. SQL allows us to choose and get only the ones we need: instead of putting the asterisk (*), we write the names of the desired columns.

SELECT name, weapon FROM "characters"

Also, in many cases we want the results be sorted in a certain way. In SQL we do this with ORDER BY. It can take an optional modifier – ASC (default) or DESC for sorting direction:

SELECT name, weapon FROM "characters" ORDER BY name DESC

Bonus: Write a query that will SELECT the name, race and hobby columns.

4. Where

You learned how to select only specific columns, but what if only certain rows need to be acquired. To the rescue here comes the WHERE clause, allowing us to filter data depending on a condition.

In this query we select only those entries from the characters table, who use a pistol to fight baddies.

Bonus: Create a SELECT query that fetches the name, race and hobby for those characters who are “Wookiees”.

5. AND / OR

WHERE conditions can be made as specific as you like, with the help of the logical operators (AND,OR) and math-like comparisons (=,,=,).

Here we have a table containing the top 4 most sold albums of all time. Let’s select those of them that are classified as rock and have sold under 50 million copies. This can easily be done by placing the AND operator between the two statements.

Bonus: Try and write an SQL query that returns the albums released after 1975 with sales less than 60 million.

6. In/Between/Like

WHERE statements also support a few special commands, allowing a quick way to check commonly used queries. They are:

  • IN – compares the column to multiple possible values, resolves true if it matches at least one
  • BETWEEN – checks if a value is within a range
  • LIKE – searches for a specific pattern

For example if we want to do a query selecting the pop and soul albums from our table, we can use IN("value1","value2").

SELECT * FROM albums WHERE genre IN ('pop','soul');

If we want to get all the albums released between 1975 and 1985 we would write:

SELECT * FROM albums WHERE released BETWEEN 1975 AND 1985;

Bonus: All of the above operations can be reversed by placing NOT in front of them. Try using NOT BETWEEN to get the albums released before 1975 and after 1985.

7. Functions

SQL is packed with functions that do all sorts of helpful stuff. Here are some of the most regularly used ones:

  • COUNT() – returns the number of rows
  • SUM() – returns the total sum of a numeric column
  • AVG() – returns the average of a set of values
  • MIN() / MAX() – gets the minimum/maximum value from a column

To get the most recent year in our table we can run:

Bonus: Try combining SUM with a WHERE clause and fetch the combined sales of all rock albums.

8. Nested Select

In the previous point we learned how to do simple calculations with data. If we want to actually use the result from these calculations, often times a nested query (also known as sub select) is necessary. Let’s say we want to get the artist, album and release year for the oldest album in the table.

We know how to get these specific columns:

SELECT artist, album, released FROM albums;

We also know how to get the earliest year:

SELECT MIN(released) FROM album;

All that is needed now is to combine the two with the help of WHERE:

Bonus: Modify the above statement to return the album, genre and year for the newest album.

9. Joining Tables

In more complex databases, most of the time there are several tables connected to each other in some way. For example, below in the editor are two tables about video games and video game developers.

In the video_games table there is a developer column, but it holds an integer instead of the name of the developer. This number represents the id of the respective developer from the game_developers table, linking logically the two sheets, allowing us to use the information stored in both of them at the same time.

If we want to create a query that returns everything we need to know about the games, we can use INNER JOIN to acquire the columns from both tables.

This is the simplest and most common type of JOIN. There are a couple of other options, but they are applicable to less frequent scenarios. Chart of SQL Joins

10. Aliases

If you look at the previous example you’ll notice that there are two columns called name. That’s confusing, so let’s change it by setting an alias to one of the repeating columns: name from game_developers will appear as developer.

We can also shorten the query drastically by setting aliases to the table names: video_games becomes games and game_developers becomes devs.

11. Update

Often times we have to change the data in some of the rows. In SQL this is done via the UPDATE statement.

The usage of UPDATE consists of

  • Choosing the table where the record we want to change is located.
  • Setting new value(s) for the wanted column(s).
  • Selecting with WHERE which of the rows we want to update. If this is omitted all rows in the table will change.

Here is a table of some of the highest rated TV series of all time. There is one tiny problem about it though, the show Game of Thrones is described as comedy, which it clearly isn’t. Let’s fix that!

Bonus: Let’s say that Breaking Bad is renewed for a new season. Write an SQL statement changing the still_running column to yes.

12. Delete Rows

Deleting a table row through SQL is a really simple process. All that is needed is to select the right table and row we want to remove.

Important: Always be cautions when writing a DELETE statement and make sure there is a WHERE clause attached. Without it all table rows will be deleted!

13. Deleting Tables

If we want to delete all the column and all the rows, but leave the table itself, the proper command is TRUNCATE:

TRUNCATE TABLE table_name;

In the case when we actually want to remove every trace of the table whatsoever, the DROP command comes into play:

DROP TABLE table_name;

Conclusion

This wraps up our tutorial on SQL! There is a lot more to cover, but the above should be enough to give you a few practical skills in your web dev career.

For more information on SQL check out these great resources:

  • Codeacademy SQL course – here
  • SQL Fiddle: online tool for testing and sharing SQL – here

Source:: Tutorialzine.com

ES.next News: a weekly email newsletter

By Axel Rauschmayer

Today, Johannes Weber and I are launching a new weekly email newsletter: ES.next News.

The concept is simple: you get 5 links related to ECMAScript 6/2015+ per week, via email. Subscribe now, it’s free:

We see ES.next News as complementary to JavaScript Weekly (which we recommend, but are not affiliated with). The former is more focused, the latter is more comprehensive.

Happy reading!

Source:: 2ality