Monthly Archives: May 2016

Six nifty ES6 tricks

By Axel Rauschmayer

In this blog post, I show six tricks enabled by new ES6 features. At the end of each section, I point to related material in my book “Exploring ES6” (which is free to read online).

Enforcing mandatory parameters via parameter default values

ES6 parameter default values are only evaluated when they are actually used. That lets you enforce that a given parameter be provided:

    /**
     * Called if a parameter is missing and
     * the default value is evaluated.
     */
    function mandatory() {
        throw new Error('Missing parameter');
    }
    function foo(mustBeProvided = mandatory()) {
        return mustBeProvided;
    }

The function call mandatory() is only made if the parameter mustBeProvided is missing.

Interaction:

    > foo()
    Error: Missing parameter
    > foo(123)
    123

More information:

Iterating over Array indices and elements via the for-of loop

Method forEach() lets you iterate over the elements of an Array. It also gives you each element’s index, should you want it:

    var arr = ['a', 'b', 'c'];
    arr.forEach(function (elem, index) {
        console.log('index = '+index+', elem = '+elem);
    });
    // Output:
    // index = 0, elem = a
    // index = 1, elem = b
    // index = 2, elem = c

The ES6 for-of loop is a loop that supports ES6 iteration (via iterables and iterators) and destructuring. If you combine destructuring with the new Array method entries(), you get:

    const arr = ['a', 'b', 'c'];
    for (const [index, elem] of arr.entries()) {
        console.log(`index = ${index}, elem = ${elem}`);
    }

arr.entries() returns an iterable over index-element pairs. The destructuring pattern [index, elem] gives us direct access to both components of each pair. The parameter of console.log() is a so-called template literal, which brings string interpolation to JavaScript.

More information:

Iterating over Unicode code points

Some Unicode code points (roughly, characters) comprise two JavaScript characters. For example, emojis:

Strings implement ES6 iteration. If you iterate over them, you get encoded code points (one or two JavaScript characters). For example:

    for (const ch of 'xuD83DuDE80y') {
        console.log(ch.length);
    }
    // Output:
    // 1
    // 2
    // 1

That gives you a way to count the number of code points in a string:

    > [...'xuD83DuDE80y'].length
    3

The spread operator (...) inserts the items “in” its operand into an Array.

More information:

Swapping variable values via destructuring

If you put two variables into an Array and then destructure that Array “into” the same variables, you can swap their values without needing an intermediate variable:

    [a, b] = [b, a];

It is conceivable that JavaScript engines will optimize this pattern in the future so that no Array is created.

More information:

Simple templating via template literals

ES6 template literals are more like string literals than like traditional text templates. But you can use them for templating if you return them from functions:

    const tmpl = addrs => `
        <table>
        ${addrs.map(addr => `
            <tr><td>${addr.first}</td></tr>
            <tr><td>${addr.last}</td></tr>
        `).join('')}
        </table>
    `;

The function tmpl (an arrow function) maps the Array addrs to a string. Let’s use tmpl() on the Array data:

    const data = [
        { first: '<Jane>', last: 'Bond' },
        { first: 'Lars', last: '<Croft>' },
    ];
    console.log(tmpl(data));
    // Output:
    // <table>
    //
    //     <tr><td><Jane></td></tr>
    //     <tr><td>Bond</td></tr>
    //
    //     <tr><td>Lars</td></tr>
    //     <tr><td><Croft></td></tr>
    //
    // </table>

More information:

Simple mixins via subclass factories

If an ES6 class extends another class, that class can is specified dynamically via an arbitrary expression (not statically via an identifier):

    // Function id() simply returns its parameter
    const id = x => x;
    
    class Foo extends id(Object) {}

That allows you to implement a mixin as a function that maps a class C to a new class (with the mixin methods) whose superclass is C. For example, the following two functions Storage and Validation are mixins:

    const Storage = Sup => class extends Sup {
        save(database) { ··· }
    };
    const Validation = Sup => class extends Sup {
        validate(schema) { ··· }
    };

You can use them to compose a class Employee as follows.

    class Person { ··· }
    class Employee extends Storage(Validation(Person)) { ··· }

More information:

Source:: 2ality

10 Fun Browser Games For Learning Web Development

By Danny Markov

10-fun-browser-games

Playing video games often involves solving tricky problems with logical thinking and trial-and-error strategies. Can you think of something else that requires these skills? That’s right – programming!

In this article we’ve prepared for you 10 browser games for web developers and coders, that you can use to learn more about JavaScript, CSS and HTML, or as a proving ground for your webmaster skills. Some of the games are easy, others extremely difficult, but they are all fun!


Code Combat

Although Code Combat is made for children in school, the game can still be enjoyed by adults of all ages. In it you programatically control the actions of a brave hero going through hundreds of dungeons, fighting enemies and collecting gems. Beating the whole game takes about 20+ hours and covers most programming concepts.


Hex Invaders

In this version of the classic arcade game the world is attacked by a trio of aliens, each sporting a different color. To save humanity, the player must quickly translate a RGB hex value into human colors and shoot down the invaders.


Flexbox Froggy

Puzzle game where you have to help a group of colorful frogs get to their lillypads of choice. Moving the amphibians around is done with flexbox and will truly test you layout building skills. The in-game hints will tell you which CSS properties to use in each situation, but it’s up to the player to decide what combination of values to set.


Pixactly

Pixactly has a very simple, yet challenging concept. The game gives you two random pixel values, one for the width and one for the height of a rectangle. The player then has to draw a box that is as close as possible to the given dimensions.


CSS Diner

A great game for learning CSS selectors. The player is given a table of dishes in animated and HTML form, and a certain item or items to select from the table. The different levels cover everything a web developer should know about selectors, from the very basics to ~ and :first-child.


Screeps

You can think of this game as your digital ant farm where every “ant” is programmed by the player. After setting up a colony and the behavior of your creeps, they will go about their business of exploring the endless game world, collecting resources and fighting enemies even while you are offline.


CodinGame

A huge collection of games that can all be played in JavaScript, PHP, Ruby, Go, Python, and many other programming languages. The platform includes various puzzle, multiplayer and AI based games, while the code is written in an advanced IDE with Emacs and Vim support.


Flexbox Defence

Classic tower defense game with a CSS twist – all the turrets and traps in the game are positioned using the flexible box layout. There are 12 levels with waves of enemies trying to reach your base. To complete them all you will have to apply your entire knowledge of flexbox properties.


Elevator Saga

Elevator Saga is a puzzle game in which you use JavaScript to control the elevators in a building. Hordes of people are going up and down all the time and you have to try and get them to their destinations as quickly as possible. The game tests your algorithm writing abilities as well as your knowledge of JS functions, arrays and event handlers.


Untrusted

Untrusted is a meta-JavaScript adventure game where you play the role of Dr. Eval, an @ sign that can control the world around him by changing the source code. The player is presented with the functions that initialize every level and has to alter them using the game API to create and escape route for Dr. Eval.


Bonus: Dungeons & Developers

A talent tree with CSS, HTML and JavaScript magic instead of fire and ice. Add points in the skill you already know and see how close you are to becoming a true Web Development Master. Submit talent tree as CV for job applications at your own risk.

Source:: Tutorialzine.com

template-literal-whitespace

By Axel Rauschmayer

In this blog post, we look at problems that arise when template literals contain whitespace:

  • Breaking up long lines
  • Dedenting content
  • Joining Arrays
  • Indenting inserted content

I’m using the library common-tags by Declan de Wet (with “useful template literal tags for dealing with strings in ES6”) to demonstrate solutions for some of these problems.

Breaking up long lines

Occasionally, you have long lines that you want to break up. common-tag’s tag function oneLine lets you do that:

    console.log(oneLine`
    a
    single
    line
    with
    many
    words
    `);
    // a single line with many words

Dedenting content

Template literals let you embed multi-line text content inside JavaScript. The main challenge is that the text must both have proper indentation and fit nicely into its JavaScript surroundings:

    function foo() {
        console.log(`<ul>
        <li>first</li>
        <li>second</li>
    </ul>`);    
    }

This does not look good: The initial

    is out of place at the end of the line and subsequent lines don’t respect JavaScript’s indentation. The output of foo() looks like this:

        <ul>
            <li>first</li>
            <li>second</li>
        </ul>
    

    As a work-around one can use trim() to gain more freedom w.r.t. the first and the last line:

        function foo() {
            console.log(`
        <ul>
            <li>first</li>
            <li>second</li>
        </ul>
        `.trim());    
        }
    

    The output is the same and the embedded text looks nicer, but the indentation problem remains. A tag function like common-tag’s stripIndent can help:

        function foo() {
            const ul = stripIndent`
                <ul>
                    <li>first</li>
                    <li>second</li>
                </ul>
                `;    
        }
    

    The idea is to determine which line has the smallest indent and to remove that indent from all lines. Additionally, leading and trailing whitespace is trimmed.

    Joining Arrays

    If you use template literals for templating, you often write code like this:

        console.log(stripIndent`
            <ul>
                ${['foo', 'bar'].map(x => `<li>${x}</li>`).join('n')}
            </ul>
        `);
    

    The problem is that the output is not properly indented:

        <ul>
                <li>foo</li>
        <li>bar</li>
            </ul>
    

    That’s because the line breaks inserted via join() are not followed by the correct indentation.

    common-tags has the tag function html which detects Arrays returned from substitutions (${}) and inserts them correctly. No need for join(), anymore:

        console.log(html`
            <ul>
                ${['foo', 'bar'].map(x => `<li>${x}</li>`)}
            </ul>
        `);
    

    Now the output looks like this:

        <ul>
            <li>foo</li>
            <li>bar</li>
        </ul>
    

    Indenting inserted content

    Alas, common-tags does not indent inserted strings correctly:

        console.log(`
            <ul>
                ${'<li>foo</li>n<li>bar</li>'}
            </ul>
            `);
    

    Here, the output is:

        <ul>
                <li>foo</li>
        <li>bar</li>
            </ul>
    

    The line break between the

    and the

  • is not followed by the correct indentation.

    Further reading

    Source:: 2ality

15 Interesting JavaScript and CSS Libraries for May 2016

By Danny Markov

interesting-libraries

Our mission at Tutorialzine is to keep you up to date with the latest and coolest trends in web development. That’s why every month we release a collection of some of the best resources that we’ve stumbled upon and deemed worthy of your attention. This May our list includes JS libraries for better scrolling, jQuery plugins for creating modals, a web boilerplate from Google, and much more!


Hint.css

Pure CSS library for adding tooltips to HTML elements. Hint is very compact in size, while still managing to offer lots of options for customization such as different sizes, colors and animations. It doesn’t require any coding, tooltips are created and styled by just adding the right data attributes.


Turntable.js

With Turntable.js you can effortlessly create cool rotating demos for 3D objects by placing a large array of images into a on-hover slider. This enables users to quickly go through the whole set of pictures, creating a flipbook effect and showcasing a product from all sides.


Magic

Magic is an animation library made entirely out of vanilla CSS. This makes it extremely lightweight and easy to use, as well as buttery smooth. All animations are triggered through adding or removing classes, and can be customized by simply overwriting the default CSS rules.


Sausage

Sausage is a jQuery tool that follows the scrollbar and keeps track of which section in a page we are reading. This plugin can be of great help when designing a big documentation hub or an infinite scrolling website, since a vertical pagination will keep things way more organized.


Odometer

The new word I learned today is odometer – that’s what the mileage gauge in a car is called. This JavaScript library with the same name recreates that gadget and can be used to add vertical transitions between numbers. It’s lightweight, easy to implement, and sports a number of great looking themes such as slot machine and train station.


FullPage.js

These days we see more and more websites use the full screen slide effect, where one touch of the scroll wheel changes the entire page. Unless you are extremely DIY oriented, this library is the perfect tool for implementing such functionality – it’s elementary to use, has detailed docs, and offers great browser support.


Chart.js

Awesome library for creating eye-catching animated charts. For better performance, Chart.js relies on canvas elements to draw all the graphs, but doesn’t require of you to know anything about canvas to work with it. All the customization options (and there are a ton of them) are controlled through a simple JavaScript API.


Bricklayer

JavaScript library for building Pinterest-like cascading grids. Working with Bricklayer isn’t complicated at all and in no time you will have a robust, repsonsive layout. It also has no external dependencies, which makes it really easy to integrate with Angular, React, or any other big framework.


Flatmarket

Flatmarket is an open-source project that provides one of the cheapest and easiest to operate platforms for e-commerce. It consist of a static website for the customers and a Node.js server that handles all the payments. A CLI tool is available that makes setting up a store from scratch much simpler.


Modaal

Modaal is a jQuery plugin for creating modal popup windows that has accessibility as it’s top priority. It provides many features that make sure the end product is available to everybody, easily readable and optimized for screen readers. Some of the good practices used in Modaal are adding keyboard controls, including ARIA attributes and maintaining proper focus.


Web Starter Kit

Web Starter Kit is a collection of tools that will help developers quickly set up their projects. It’s designed by Google and focuses on providing a boilerplate that works equally well across different devices and browsers. Some of the libraries included in this kit are MDL, Sass, Babel, and gulp for task automation.


Flipside

This is a button that transforms into a dialog. The cool thing about it is the transition, which varies depending on which part of the button the user clicked. Flipside isn’t a proper library but we enjoyed it a lot so we decided to share it anyway. If you want to use it, the source code is available on GitHub.


Responsify.js

Responsify is a jQuery plugin that guarantees an image remains responsive and showing the right content. This is done by adding an attribute to tags, where a focus area is defined. If the image has to be resized, Responsify will try and keep the focus area visible, and hide parts of the image that are less important.


Select2

Select boxes are still astronomically annoying to style across all browsers. Thankfully, there are plugins like Select2 which deal with that issue and offer painless embellishment of the select element and it’s options. This library also has useful extra features such as searching, infinite scrolling and IE8 support.


Vex

A tiny jQuery plugin for creating dialog pop-ups with a neat fake-3D animation effect. This library is only 2kb minified and gzipped so it practicly costs nothing to include in a project. It has a couple of available themes, and you can add your own customizations fairly easily as well.

Source:: Tutorialzine.com