Future

Rust and the Future of Systems Programming

If you’re a regular reader of Hacks, you probably know about Rust, the ground-breaking, community-driven systems programming language sponsored by Mozilla. I covered Rust on Hacks back in July, to note a major milestone for Mozilla, when we shipped Rust in Firefox for the first time.

Meanwhile in Rust-land, the trains keep on rolling, more users are putting Rust in production, and the ecosystem and worldwide community continue growing. And our investment at Mozilla is growing too! There’s been a lot of news and excitement lately about Project Quantum, which leverages the innovations of the Servo web engine, another vibrant open source community sponsored by Mozilla.

So we’ve created a video series to tell the world about Rust, to celebrate the incredible community, and to demonstrate our investment in Rust and its long-term success. Today, we are publishing Rust and the Future of Systems Programming, the first in our six-part series. Visit our Mozilla Tech Medium publication over the next week to view each video as it is released or head over to Mozhacks YouTube to subscribe to the complete series:

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Future Decoded 2016 – My talk on Machine Learning, Terminators and Star Trek

Yesterday I went to the Excel in London for Future Decoded to learn a lot about the future of technology, finally see the DeLorian from Back to the Future and give a talk. I covered Machine Learning, its ethics, its effects on the job market and what we as developers need to do to make Artificial Intelligence work for rather than against humans.

DeLorian from Back to the Future

Apparently it was more relaxing that the Great British Bake Off:

Sadly, there was no video recording, but I recorded my own screencast again. The video is on YouTube

The slides are available on SlideShare.

I will repeat this talk slightly amended and more about the ethics and ideas as the Friday Keynote of the upcoming Øredev Conference in Malmø so see you there?

View full post on Christian Heilmann

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

The future of layout with CSS: Grid Layouts

In this article we’ll take a look at the wonderful world of the CSS Grid Layout, a relatively new W3C specification that has partially started to see the day in some browsers.

But before we dive into what this new CSS technique is all about and how to use it, let’s quickly review grid theory.

My really short introduction to grid theory

I am not a designer nor did I know much about grid theory before stumbling upon the CSS Grid Layout specification, so don’t take my word for it and go look it up yourself, but if you don’t care to, here’s my pitch:

In essence, a grid is a set of invisible vertical and horizontal lines that are used to position the various design and content pieces of a web page, magazine, or newspaper. The goal of a grid is to serve as a base for placing the various pieces of content and to make sure these pieces are aligned and spaced out evenly. A grid, even if not visible, provides the viewer with a way to navigate content visually.

So what has CSS got to do with it?

CSS is getting a set of entirely new properties that, when used together, allow you to define grids for your web content to go onto. These properties are defined in the CSS Grid Layout specification.

CSS hasn’t particularly been known for its ability to handle complex layouts. Although this may not have been a problem when CSS first came out, it has evolved to be a pretty common one over the years, as all sorts of complex layouts couldn’t be easily implemented. People have been very creative at getting around the lack of support by using floats or absolute positioning and a variety of CSS layout frameworks emerged.

So it’s about time CSS got some proper layout solutions to support today’s use cases.

Can I use it?

Yes you can start using it today, to experiment and learn. It’s a bit too early to use it on a commercial website.

Chrome has implemented the specification far enough to play with Grid. Turn the experimental Web Platform features flag on to get it to work. The Chrome implementation is currently the most up-to-date with the recent changes to the CSS Grid Layout specification.

Internet Explorer had the first implementation of CSS Grid (dating back to IE10), but the spec has evolved since it was added and so it’s not entirely compatible with the latest spec anymore. They’ll be updating their implementation soon.

Firefox has started implementing it too, so it shouldn’t be too long before you can use it in this browser.

Finally, a polyfill exists, so you have no excuses not to start experimenting. (And I strongly encourage you to do so!) You probably should not use the polyfill in production, however.

So what’s a CSS grid layout?

At its core, a grid layout in CSS is a set of vertical and horizontal lines that define cells into which content can be arbitrarily positioned.
So it looks like a table in a way, except for a few key differences we’ll see later.

1 zcOcwuBtMoBaUfHHAJPNyg

The figure above shows the building blocks of a grid:

  • Lines: In this case there are 4 vertical lines and 3 horizontal lines. Lines are given numbers starting from 1. Vertical lines are shown from left to right, but this depends on the writing direction. Lines can optionally be given names, which helps with referencing them in CSS, as we’ll see later.
  • Tracks: A track is simply the space between 2 parallel lines. So in the above example, there are 3 vertical tracks and 2 horizontal tracks. Lines are useful to indicate where content starts and stops, but tracks are ultimately where content goes.
  • Cells: A cell is where a horizontal and a vertical track meet. In the figure above, only one cell has been highlighted, but there are 6 cells in the grid.
  • Areas: An area is a rectangular shape that can span an arbitrary number of cells. Areas, like lines, can be named. In the above grid, we could for example define areas A, B and C as shown below:

1 zcOcwuBtMoBaUfHHAJPNyg

Now that we know these simple definitions, let’s take a look at what makes grids so powerful.

One key advantage of CSS grids is that they enforce real separation of layout and markup.

Indeed, the grid itself is completely defined in pure CSS. This means that apart from the parent HTML element the grid is applied to, there’s no need to define any extra elements for the columns, rows, cells, or areas.

When you think of it, that’s a really interesting property. One aspect of it is that the visual order of elements on the page is decoupled from the order of elements in the markup. That’s important because on a page the source order is used for things like speech and tab navigation, so CSS Grids allow you to optimize the markup for accessibility without compromising your ability to manipulate the visual result. One other point is that the markup will be somewhat lighter and easier to understand, and therefore easier to maintain.

But more importantly, it gives us a very powerful tool for separating the content from the layout, effectively decoupling them in a way that makes it possible to change one without impacting or otherwise breaking the other.
As a designer, you can easily experiment with new layouts without having to change anything other than CSS, as long as your new layouts provide the expected lines and areas the content uses.
And as a developer, you simply use the numbered or named lines and areas to position your content on the grid.

Imagine the simple following grid layout:

1 zcOcwuBtMoBaUfHHAJPNyg

In this layout, named areas have been defined, allowing content to be positioned in them simply by referencing the names. This means that not only can we change this layout relatively easily in the future, as long as we maintain the named regions (here the named regions act as the layout’s public API in a way), but media-queries can be used to change this layout dynamically too. Remember, the whole layout is defined in CSS, so media-queries play with grid layouts very well.

For instance, using a media query, the previous layout could switch to something like this on smaller screens:

1 zcOcwuBtMoBaUfHHAJPNyg

Enough with the theory, let’s see how grid layouts are actually defined using CSS.

Creating grids with CSS

Defining a grid requires only one HTML element to be present: the grid container. That’s the element the layout is going to be applied to. Any HTML element that’s a child of the grid container is a grid item. Grid items are what go onto the grid.

Setting an element as being a grid container is as simple as:

.container { display: grid; }


Just doing this though isn’t nearly enough, we also need to define what this grid looks like, how many columns and rows it has, and how big they are.
This can be done using grid templates as shown in the following example:

.container {
  display: grid;
  grid-template-rows: 200px 100px;
  grid-template-columns: repeat(4, 100px);
}


In the example above, we’re explicitly defining a grid that has 2 rows and 4 columns. Note how the repeat() function is used here to avoid repeating a fragment of the tracks 4 times, this is equivalent to 100px 100px 100px 100px.

Each of the defined tracks is given a size, and so we end up with a grid structure that looks like this:

1 zcOcwuBtMoBaUfHHAJPNyg

But grids can also be implicitly defined like in:

.container {
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: repeat(4, 100px);
}


In this case, the browser will keep on adding rows as needed to fit the content.

Now let’s add some content. As we said previously, we only need 2 levels of elements, the container and the items, so let’s use this:

<div class="container">
  <div class="item1">item 1</div>
  <div class="item2">item 2</div>
  <div class="item3">item 3</div>
  <div class="item4">item 4</div>
  <div class="item5">item 5</div>
</div>


Which, without any specific CSS code to position the items, leads to the following arrangement:

1 zcOcwuBtMoBaUfHHAJPNyg

As you can see above, since we didn’t define where these items should sit on the grid, the browser has positioned them automatically by putting one item per cell until the first row got filled in, at which point it decided to put the rest of the items on the next row.

The spec defines an algorithm for automatically placing items on the grid if they haven’t been given a position. This is sometimes useful when, for example, you have either many items or a dynamic number of items and don’t want to or can’t define the position for them all.

Let’s see how our items can be positioned on the grid.

.item1 {
  grid-row-start: 1;
  grid-row-end: 2;
  grid-column-start: 1;
  grid-column-end: 3;
}
.item2 {
  grid-row-start: 1;
  grid-row-end: 2;
  grid-column-start: 3;
  grid-column-end: 5;
}


Here we’ve defined the position of the 2 first items, which means that the other ones will still be automatically positioned by the browser, as shown below:

1 zcOcwuBtMoBaUfHHAJPNyg

The above example uses line-based placement in that it uses numeric indexes of lines to place items. Items 1 and 2 are defined to be positioned between horizontal lines 1 and 2, and between vertical lines 1 and 3 and 3 and 5.

What happens now if we keep on adding items, but there aren’t any grid cells defined to receive them?

1 zcOcwuBtMoBaUfHHAJPNyg

The grid keeps on adding rows and columns as needed. Note that these new tracks will have their sizes depend on the content size.

So that’s all well and good, but one thing that’s really useful when it comes to CSS Grids is grid areas, as we saw earlier. Let’s take a look at how grid areas can be used in CSS.

First of all you’ll need to define the grid container and its tracks and areas:

.container {
  display: grid;
  grid-template-rows: 100px auto 100px;
  grid-template-columns: 100px auto;
  grid-template-areas:
    "header  header"
    "sidebar content"
    "footer  footer";
}


In this example, we’ve defined 3 rows, the top and bottom ones being 100px high, while the middle one will just adapt to its content. We’ve also defined 2 columns, the left one 100px wide, and the right one adapting to its content.

We’ve also introduced the grid-template-areas property that may look strange at first, but it’s really simple when you realize it’s only a representation of the grid with names on it. Let’s explain this.

We said we had 3 rows and 2 columns right? Let’s represent them in ascii-art like this:

+---+---+
| . | . |
+---+---+
| . | . |
+---+---+
| . | . |
+---+---+


Each dot is a cell where areas can be defined. So let’s define areas for a typical website layout:

+--------+--------+
| header | header |
+--------+--------+
| sidebar| content|
+--------+--------+
| footer | footer |
+--------+--------+


We want the header and footer to span the whole width, so we’ve repeated them in the 2 columns.
Now, if we just remove all the useless ascii-art style borders and include each line in double-quotes, we get something like this:

"header  header"
"sidebar content"
"footer  footer"


which is exactly how grid areas are defined in CSS using the grid-template-areas property. It helps thinking about it as a 2D representation of the grid in ascii-art and aligning area names.

You can also use dots ‘.’ when a cell isn’t covered by an area. Here’s an example:

.container {
  display: grid;
  grid-template-rows: repeat(5, 100px);
  grid-template-columns: repeat(5, 100px);
  grid-template-areas:
    ". . . . ."
    ". . . . ."
    ". . a . ."
    ". . . . ."
    ". . . . .";
}


In this example, there are 25 cells and 1 area that is defined to occupy only the center cell.

Now, going back to the previous header, sidebar, content, footer example, let’s add some markup to it:

<div class="container">
  <div class="header">header</div>
  <div class="sidebar">sidebar</div>
  <div class="footer">footer</div>
  <div class="content">
    <p>Lorem ipsum dolor sit amet...</p>
 </div>
</div>


The last thing that needs to be done now is position each grid item in the correct named areas (we’ve conveniently used class names that correspond to area names here):

.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.footer { grid-area: footer; }
.content { grid-area: content; }


Which would produce something like this:

1 zcOcwuBtMoBaUfHHAJPNyg

Now, if we wanted to change this layout at any point, or make it adapt to variable screen sizes thanks to media queries, we would only have to change the grid declaration. Maybe to something like this:

.container {
  display: grid;
  grid-template-rows: auto;
  grid-template-columns: 100%;
  grid-template-areas:
    "header"
    "sidebar"
    "content"
    "footer";
}


Without any other changes to the CSS or markup, we’ve produced this:

1 zcOcwuBtMoBaUfHHAJPNyg

We could even completely reshuffle the order of items in the grid without having to change their order in the markup.

CSS Grids in the real world

So far we’ve only seen simplistic examples of grids, but websites making use of grid systems often have much more complex grid structures. It’s not uncommon for such websites to be based on 12 columns, each of them separated by gutters (narrower columns used to space things out).

Take dribbble.com for example, this design showcase website makes use of a grid to display the designs uploaded by their users. Here the grid is very easily visible because each design occupies exactly one cell (excluding gutter rows and columns):

Dribbble’s grid layout is also responsive, so if the viewport size changes, the size and number of columns change gradually, as shown in the following animation:

Using the new properties that come with the CSS Grid Layout implementation, we can try and create a dribbble-like layout. For an added twist, let’s try and insert a piece of text content on the second row, and make that content span the whole row.

First of all, our markup will be something like this:

<ul class="dribbbles">
  <li class="dribbble">...</li>
  <li class="dribbble">...</li>
  ...
  <li class="dribbble">...</li>
  <li class="advert">Some text ....</li>
</ul>


Here the dribbbles element is the main container for all items, and each .dribbble element represents one of the designs showcased on the page. The last item, .advert, is the piece of textual content we want to show on the second row.

Now, let’s make a grid for it:

.dribbbles {
  display: grid;
  /* Let's assume the default design has a fixed width */
  width: 880px;
  grid-template-columns: repeat(4, 220px);
  grid-template-areas:
    ".      .      .      ."
    "advert advert advert advert";
  justify-items: center;
}
.advert {
  grid-area: advert;
}


Here we’ve defined 4 columns in our grid. We haven’t said anything about rows, so the browser will automatically create rows as needed.
We did, however, define a couple of rows using the grid-template-areas property and that’s because we need to place our advert text content on the second row. So we’ve just said that we want a first row with empty cells that are going to be filled in automatically with grid items, as they come, and then a second row that defines an advert area that spans all 4 columns.

Finally, the second rule in there uses the grid-area property to place the grid item that has the class advert inside the advert area.

Given the markup we created earlier, this should end up looking something like this:

Pretty simple, right? Of course this requires some styling code to make the items look nice and all, but the layout CSS code is really short and there’s no extra markup required.

Now, we can make this responsive too. Let’s say we want to jump to a 3-columns layout for smaller screens:

@media (max-width: 880px) and (min-width: 660px) {
  .dribbbles {
    width: 660px;
    grid-template-columns: repeat(3, 220px);
    grid-template-areas:
      ".      .      ."
      "advert advert advert";
  }
}


And so on, for all the screen sizes we want to support. And so, just adding a couple more short media queries, we could end up with something like this:

Sites like Dribbble don’t use the CSS Grid Layout yet, but there are well known CSS libraries that provide grid systems.

A good example of a grid system in CSS is the Bootstrap CSS library but there are others like PureCSS, 960 Grid System, Responsive Grid System, Materialize, and more.

These grid systems unfortunately have to use arrangements of carefully sized and floated DIVs, and need extra DIVs for columns and rows, as well as pseudo-elements for clearing floats. It’s not all that complex—after all, the tricks that these libraries rely on have been known for years—but they’re still just tricks, and it’s time we get a proper built-in solution and get rid of them.

Don’t get me wrong, these libraries are awesome in all sorts of way, and most importantly, they helped make it clear we needed a new CSS feature for defining grids in web layouts. Ultimately, therefore, they are what made the CSS Grid Layout specification possible.

Closing words and references

As we saw, CSS grids are a pretty good tool for defining layouts that have nice characteristics like authoring simplicity, maintainability, separation of content and layout — characteristics that play well with responsive design.
But we’ve only barely scratched the surface of what is possible with CSS grids. The various properties and syntax possibilities allow for a lot of really cool things to be done, and I hope this article makes you want to dig further by yourself.

Here are some interesting references if you wish to know more:

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

ES6 In Depth: The Future

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.

Last week’s article on ES6 modules wrapped up a 4-month survey of the major new features in ES6.

This post covers over a dozen more new features that we never got around to talking about at length. Consider it a fun tour of all the closets and oddly-shaped upstairs rooms in this mansion of a language. Maybe a vast underground cavern or two. If you haven’t read the other parts of the series, take a look; this installment may not be the best place to start!

(a picture of the Batcave, inexplicably)

“On your left, you can see typed arrays…”

One more quick warning: Many of the features below are not widely implemented yet.

OK. Let’s get started.

Features you may already be using

ES6 standardizes some features that were previously in other standards, or widely implemented but nonstandard.

  • Typed arrays, ArrayBuffer, and DataView. These were all standardized as part of WebGL, but they’ve been used in many other APIs since then, including Canvas, the Web Audio API, and WebRTC. They’re handy whenever you need to process large volumes of raw binary or numeric data.

    For example, if the Canvas rendering context is missing a feature you want, and if you’re feeling sufficiently hardcore about it, you can just implement it yourself:

    var context = canvas.getContext("2d");
    var image = context.getImageData(0, 0, canvas.width, canvas.height);
    var pixels = image.data;  // a Uint8ClampedArray object
    // ... Your code here!
    // ... Hack on the raw bits in `pixels`
    // ... and then write them back to the canvas:
    context.putImageData(image, 0, 0);
    

    During standardization, typed arrays picked up methods like .slice(), .map(), and .filter().

  • Promises. Writing just one paragraph about promises is like eating just one potato chip. Never mind how hard it is; it barely even makes sense as a thing to do. What to say? Promises are the building blocks of asynchronous JS programming. They represent values that will become available later. So for example, when you call fetch(), instead of blocking, it returns a Promise object immediately. The fetch goes on in the background, and it’ll call you back when the response arrives. Promises are better than callbacks alone, because they chain really nicely, they’re first-class values with interesting operations on them, and you can get error handling right with a lot less boilerplate. They’re polyfillable in the browser. If you don’t already know all about promises, check out Jake Archibald’s very in-depth article.

  • Functions in block scope. You shouldn’t be using this one, but it’s possible you have been. Maybe unintentionally.

    In ES1-5, this code was technically illegal:

    if (temperature > 100) {
      function chill() {
        return fan.switchOn().then(obtainLemonade);
      }
      chill();
    }
    

    That function declaration inside an if block was supposedly forbidden. They were only legal at toplevel, or inside the outermost block of a function.

    But it worked in all major browsers anyway. Sort of.

    Not compatibly. The details were a little different in each browser. But it sort of worked, and many web pages still use it.

    ES6 standardizes this, thank goodness. The function is hoisted to the top of the enclosing block.

    Unfortunately, Firefox and Safari don’t implement the new standard yet. So for now, use a function expression instead:

    if (temperature > 100) {
      var chill = function () {    
        return fan.switchOn().then(obtainLemonade);
      };
      chill();
    }
    

    The only reason block-scoped functions weren’t standardized years ago is that the backward-compatibility constraints were incredibly complicated. Nobody thought they could be solved. ES6 threads the needle by adding a very strange rule that only applies in non-strict code. I can’t explain it here. Trust me, use strict mode.

  • Function names. All the major JS engines have also long supported a nonstandard .name property on functions that have names. ES6 standardizes this, and makes it better by inferring a sensible .name for some functions that were heretofore considered nameless:

    > var lessThan = function (a, b) { return a < b; };
    > lessThan.name
        "lessThan"
    

    For other functions, such as callbacks that appear as arguments to .then methods, the spec still can’t figure out a name. fn.name is then the empty string.

Nice things

  • Object.assign(target, ...sources). A new standard library function, similar to Underscore’s _.extend().

  • The spread operator for function calls. This is nothing to do with Nutella, even though Nutella is a tasty spread. But it is a delicious feature, and I think you'll like it.

    Back in May, we introduced rest parameters. They’re a way for functions to receive any number of arguments, a more civilized alternative to the random, clumsy arguments object.

    function log(...stuff) {  // stuff is the rest parameter.
      var rendered = stuff.map(renderStuff); // It's a real array.
      $("#log").add($(rendered));
    }
    

    What we didn’t say is that there’s matching syntax for passing any number of arguments to a function, a more civilized alternative to fn.apply():

    // log all the values from an array
    log(...myArray);
    

    Of course it works with any iterable object, so you can log all the stuff in a Set by writing log(...mySet).

    Unlike rest parameters, it makes sense to use the spread operator multiple times in a single argument list:

    // kicks are before trids
    log("Kicks:", ...kicks, "Trids:", ...trids);
    

    The spread operator is handy for flattening an array of arrays:

    > var smallArrays = [[], ["one"], ["two", "twos"]];
    > var oneBigArray = [].concat(...smallArrays);
    > oneBigArray
        ["one", "two", "twos"]
    

    ...but maybe this one of those pressing needs that only I have. If so, I blame Haskell.

  • The spread operator for building arrays. Also back in May, we talked about “rest” patterns in destructuring. They’re a way to get any number of elements out of an array:

    > var [head, ...tail] = [1, 2, 3, 4];
    > head
        1
    > tail
        [2, 3, 4]
    

    Guess what! There’s matching syntax for getting any number of elements into an array:

    > var reunited = [head, ...tail];
    > reunited
        [1, 2, 3, 4]
    

    This follows all the same rules as the spread operator for function calls: you can use the spread operator many times in the same array, and so on.

  • Proper tail calls. This one is too amazing for me to try to explain here.

    To understand this feature, there’s no better place to start than page 1 of Structure and Interpretation of Computer Programs. If you enjoy it, just keep reading. Tail calls are explained in section 1.2.1, “Linear Recursion and Iteration”. The ES6 standard requires that implementations be “tail-recursive”, as the term is defined there.

    None of the major JS engines have implemented this yet. It’s hard to implement. But all in good time.

Text

  • Unicode version upgrade. ES5 required implementations to support at least all the characters in Unicode version 3.0. ES6 implementations must support at least Unicode 5.1.0. You can now use characters from Linear B in your function names!

    Linear A is still a bit risky, both because it was not added to Unicode until version 7.0 and because it might be hard to maintain code written in a language that has never been deciphered.

    (Even in JavaScript engines that support the emoji added in Unicode 6.1, you can’t use 😺 as a variable name. For some reason, the Unicode Consortium decided not to classify it as an identifier character. 😾)

  • Long Unicode escape sequences. ES6, like earlier versions, supports four-digit Unicode escape sequences. They look like this: \u212A. These are great. You can use them in strings. Or if you’re feeling playful and your project has no code review policy whatsoever, you can use them in variable names. But then, for a character like U+13021 (𓀡), the Egyptian hieroglyph of a guy standing on his head, there's a slight problem. The number 13021 has five digits. Five is more than four.

    In ES5, you had to write two escapes, a UTF-16 surrogate pair. This felt exactly like living in the Dark Ages: cold, miserable, barbaric. ES6, like the dawn of the Italian Renaissance, brings tremendous change: you can now write \u{13021}.

  • Better support for characters outside the BMP. The .toUpperCase() and .toLowerCase() methods now work on strings written in the Deseret alphabet!

    In the same vein, String.fromCodePoint(...codePoints) is a function very similar to the older String.fromCharCode(...codeUnits), but with support for code points beyond the BMP.

  • Unicode RegExps. ES6 regular expressions support a new flag, the u flag, which causes the regular expression to treat characters outside the BMP as single characters, not as two separate code units. For example, without the u, /./ only matches half of the character "😭". But /./u matches the whole thing.

    Putting the u flag on a RegExp also enables more Unicode-aware case-insensitive matching and long Unicode escape sequences. For the whole story, see Mathias Bynens’s very detailed post.

  • Sticky RegExps. A non-Unicode-related feature is the y flag, also known as the sticky flag. A sticky regular expression only looks for matches starting at the exact offset given by its .lastIndex property. If there isn’t a match there, rather than scanning forward in the string to find a match somewhere else, a sticky regexp immediately returns null.

  • An official internationalization spec. ES6 implementations that provide any internationalization features must support ECMA-402, the ECMAScript 2015 Internationalization API Specification. This separate standard specifies the Intl object. Firefox, Chrome, and IE11+ already fully support it. So does Node 0.12.

Numbers

  • Binary and octal number literals. If you need a fancy way to write the number 8,675,309, and 0x845fed isn’t doing it for you, you can now write 0o41057755 (octal) or 0b100001000101111111101101 (binary).

    Number(str) also now recognizes strings in this format: Number("0b101010") returns 42.

    (Quick reminder: number.toString(base) and parseInt(string, base) are the original ways to do convert numbers to and from arbitrary bases.)

  • New Number functions and constants. These are pretty niche. If you’re interested, you can browse the standard yourself, starting at Number.EPSILON.

    Maybe the most interesting new idea here is the “safe integer” range, from −(253 - 1) to +(253 - 1) inclusive. This special range of numbers has existed as long as JS. Every integer in this range can be represented exactly as a JS number, as can its nearest neighbors. In short, it’s the range where ++ and -- work as expected. Outside this range, odd integers are representable as 64-bit floating-point numbers, so incrementing and decrementing the numbers that are representable (all of which are even) can’t give a correct result. In case this matters to your code, the standard now offers constants Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER, and a predicate Number.isSafeInteger(n).

  • New Math functions. ES6 adds hyperbolic trig functions and their inverses, Math.cbrt(x) for computing cube roots, Math.hypot(x, y) for computing the hypotenuse of a right triangle, Math.log2(x) and Math.log10(x) for computing logarithms in common bases, Math.clz32(x) to help compute integer logarithms, and a few others.

    Math.sign(x) gets the sign of a number.

    ES6 also adds Math.imul(x, y), which does signed multiplication modulo 232. This is a very strange thing to want... unless you are working around the fact that JS does not have 64-bit integers or big integers. In that case it’s very handy. This helps compilers. Emscripten uses this function to implement 64-bit integer multiplication in JS.

    Similarly Math.fround(x) is handy for compilers that need to support 32-bit floating-point numbers.

The end

Is this everything?

Well, no. I didn’t even mention the object that’s the common prototype of all built-in iterators, the top-secret GeneratorFunction constructor, Object.is(v1, v2), how Symbol.species helps support subclassing builtins like Array and Promise, or how ES6 specifies details of how multiple globals work that have never been standardized before.

I’m sure I missed a few things, too.

But if you’ve been following along, you have a pretty good picture of where we’re going. You know you can use ES6 features today, and if you do, you’ll be opting in to a better language.

A few days ago, Josh Mock remarked to me that he had just used eight different ES6 features in about 50 lines of code, without even really thinking about it. Modules, classes, argument defaults, Set, Map, template strings, arrow functions, and let. (He missed the for-of loop.)

This has been my experience, too. The new features hang together very well. They end up affecting almost every line of JS code you write.

Meanwhile, every JS engine is hurrying to implement and optimize the features we’ve been discussing for the past few months.

Once we’re done, the language will be complete. We’ll never have to change anything again. I’ll have to find something else to work on.

Just kidding. Proposals for ES7 are already picking up steam. Just to pick a few:

  • Exponentation operator. 2 ** 8 will return 256. Implemented in Firefox Nightly.

  • Array.prototype.includes(value). Returns true if this array contains the given value. Implemented in Firefox Nightly; polyfillable.

  • SIMD. Exposes 128-bit SIMD instructions provided by modern CPUs. These instructions do an arithmetic operation on 2, or 4, or 8 adjacent array elements at a time. They can dramatically speed up a wide variety of algorithms for streaming audio and video, cryptography, games, image processing, and more. Very low-level, very powerful. Implemented in Firefox Nightly; polyfillable.

  • Async functions. We hinted at this feature in the post on generators. Async functions are like generators, but specialized for asynchronous programming. When you call a generator, it returns an iterator. When you call an async function, it returns a promise. Generators use the yield keyword to pause and produce a value; async functions instead use the await keyword to pause and wait for a promise.

    It’s hard to describe them in a few sentences, but async functions will be the landmark feature in ES7.

  • Typed Objects. This is a follow-up to typed arrays. Typed arrays have elements that are typed. A typed object is simply an object whose properties are typed.

    // Create a new struct type. Every Point has two fields
    // named x and y.
    var Point = new TypedObject.StructType({
      x: TypedObject.int32,
      y: TypedObject.int32
    });
    
    // Now create an instance of that type.
    var p = new Point({x: 800, y: 600});
    console.log(p.x); // 800
    

    You would only do this for performance reasons. Like typed arrays, typed objects offer a few of the benefits of typing (compact memory usage and speed), but on a per-object, opt-in basis, in contrast to languages where everything is statically typed.

    They’re are also interesting for JS as a compilation target.

    Implemented in Firefox Nightly.

  • Class and property decorators. Decorators are tags you add to a property, class, or method. An example shows what this is about:

    import debug from "jsdebug";
    
    class Person {
      @debug.logWhenCalled
      hasRoundHead(assert) {
        return this.head instanceof Spheroid;
      }
      ...
    }
    

    @debug.logWhenCalled is the decorator here. You can imagine what it does to the method.

    The proposal explains how this would work in detail, with many examples.

There’s one more exciting development I have to mention. This one is not a language feature.

TC39, the ECMAScript standard committee, is moving toward more frequent releases and a more public process. Six years passed between ES5 and ES6. The committee aims to ship ES7 just 12 months after ES6. Subsequent editions of the standard will be released on a 12-month cadence. Some of the features listed above will be ready in time. They will “catch the train” and become part of ES7. Those that aren’t finished in that timeframe can catch the next train.

It’s been great fun sharing the staggering amount of good stuff in ES6. It’s also a pleasure to be able to say that a feature dump of this size will probably never happen again.

Thanks for joining us for ES6 In Depth! I hope you enjoyed it. Keep in touch.

View full post on Mozilla Hacks - the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Øredev 2013 – The very near future of a richer, standards based web

I am currently at Øredev in Malmø, Sweden, and this morning I spoke about “The very near future of a richer, standards based web”.

Chris Heilmann, presenting
photo by Fredrik Frodlund

My talk covered new technologies people should be using to make them a reality rather than waiting for a perfect reality and full support across all browsers to happen magically. A screencast of the talk is available on YouTube.

One thing I mentioned in my talk is the great survey results by Visionmobile on Web competing with mobile. If you want to ensure more real data being covered in talks, please help them by taking part in their Q4 survey – it is 5 minutes of your time and you can even win some neat stuff.

Links covered:

I am speaking tomorrow about Firefox OS at the same conference.

View full post on Christian Heilmann

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

One step ahead and two steps back: are apps really the future?

My esteemed colleague Luke Crouch put together an interesting piece entitled Packaged HTML5 Apps – are we emulating failure which resonates quite well with me. In it he describes the process of scanning a QR code on a phone to check into a restaurant with Facebook. This right now involves installing a QR code reader, the Facebook app and many in-between steps that can not be in the best interest of the restaurant owner and requires a lot of patience from the user.

Software!

My reservations towards QR codes aside (hey, with NFC, this would be “tap your phone here to check in” – you hear that, Apple?) I think Luke points to a much bigger topic here that very much annoys me: we are stalling, if not moving backwards in the evolution of content delivery.

Let’s reduce the use case to the bare minimum here: an end user wants to get some content. This could be music, video, photos, a book, a map with instructions or a game to play. It all is data, zeroes and ones that if arranged in the right format make up the thing I want. Our job as the data providers should be not to throw as many barriers in the way of the consumer to reach that – our job should be to make this dead easy.

Whenever people say that “users want apps” then what they really say is “people want a thing that uses their hardware to the best of its abilities and be able to find that in a simple way”. Doesn’t roll as well of the tongue and sucks as a rallying cry, but describes the thing much better. I remember the days before the Internet, when software came on floppy disks in the mail and had to be installed and the third install disk had a read/write error so you had to call the company or go back to the shop to get a replacement. I also remember having to install a tool to cut up images for table layouts or to plan a route for my holidays. I also remember buying games and being told my computer is not good enough – always the sound card, which wasn’t as “Soundblaster compatible” as it pretended to be.

This seems ridiculous now and we laugh at the idea of not being able to just type, “Hackney, London” into the search box of our phone or browser and get a map back. Yet this is exactly the world we seem to crave to go back to when we say that apps are a much better experience and the future of our jobs and what people want.

What we do by praising apps and their simplicity is reward companies for locking users out – demanding the real Soundblasters so to say. We claim that app stores are easier for recovery and yet these companies pay a lot of money to advertise their apps and games on TV, in newspapers and in banner ads on the web. App stores are not easier. They do not scale. I wait for the day – which will come very soon indeed – where you can buy better placement in app stores, much like you could in “price comparison web sites” and search results.

If you took the app store model and compare it with something that happened to the web then app stores are the Yahoo directory which got killed by search with Google being the big innovator. We realised that it is far too much work to curate and edit a list of web resources when the format of them would allow publishers to promote their content and make the amount of people clicking it determine what gets shown first.

If you care to remember, we already had a failed attempt at app stores. Tucows, Download.com, Freshmeat.net and others tried the same for Desktop apps and nobody cares about them right now any longer and they fall into disarray and become a spammer’s heaven.

The focus on apps right now and the repeated myth that they are a much better experience for end users than the web are based on man-made barriers for the web:

  • Apps have much more access to the device’s hardware
  • App stores are promoted with the sale of the hardware

For everyone proclaiming that app stores are the better way to distribute apps I propose to check out the hundreds of empty app stores mobile service providers set up or the ones of hardware that is less successful than Android or iPhone. Wastelands full of frivolous apps and overpriced quickly converted and packaged old titles that were a success on other platforms.

This is not about what users want – this is about what the industry and distributors are used to and don’t want to change. A packaged app can be much easier priced and its distribution planned and tracked than a web app. Much like physical CDs and DVDs and books still have quite some time to vanish, the packaged app to me is the last of the dinosaurs when physical distribution was all you could do.

A lot needs to change till we realise that we have a wonderful way to distribute media called the Internet. Media that can stay fresh, can get updated when we need and discarded when we don’t want it any longer without having to download lots and lots of data each time.

Most of it is based on business models that are not flexible and see full control over the distribution as the only means of making money. Some of it is psychological. A neatly packaged app you need to install and uninstall seems like something more solid than a web app. It seems more trustworthy, whilst it also can cause much more damage. It is the “20% more” on a fizzy drink can you never knew you missed so much.

I am very afraid that if we do not stand our ground now and point out that apps are a distribution model of the past and not the future we’ll repeat the same mistake we did with Application directories in the past. Of course you can now list 23123 reasons why apps are better than web apps on mobile devices, but I dare you to find one that is not based on the device or OS vendor blocking access to functionality for non-native code. We praise a model of distribution for its simplicity based on lockout.

The argument you hear about this is that end users don’t care, they just want their apps. The fact here is that they don’t get told about alternatives. Again it is all marketing – damn good marketing, admittedly – but many demands from our end users come from seeing something and wanting it rather than needing it in the first place.

View full post on Christian Heilmann

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)