Monthly Archives: February 2016

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

20 Interesting JavaScript and CSS Libraries for February 2016

By Dimo Raichev

interesting-resources-february

The world of web development keeps expanding as new frameworks, libraries and plugins are created everyday. To keep you up to date with all the cool toys, we made this collection of our favorite JavaScript and CSS tools you should try in February 2016.


Super Simple Slider

Super simple slider is jQuery plugin which provides you with a functional and lightweight slider. To set it up just place your content in an empty element and call the plugin. If your content is of different heights, the plugin will animate smoothly to accommodate it.


Chartist

Chartist.js

Chartist is a JavaScript library which helps you present your charts in interesting ways. With CSS animations your charts are clear and eye-catching. Chartist provides you with a simple configuration override mechanism based on media queries to help you control the behavior of your charts.


Gridle

Griddle

Griddle is a useful grid component using React. With a lot of powerful functionality like filtering, paging, infinite scrolling and sub-grids, you can easily customise it to fit your project. Rendering is optimized so that only the current page of results is generated.


Textillate

Textillate.js

Textillate.js is a jQuery plugin which uses animate.css and lettering.js to apply eye-catching animations to text. To use it, include the plugin’s JavaScript file alongside the libraries it depends on and start creating unique effects.


Slideout

Slideout.js

Slideout is a JavaScript library which helps you set up touch slideout navigation menu for your mobile web apps. It doesn’t have any dependencies, has simple markup and uses native scrolling, so that it works smoothly on mobile devices.


Awesomplete

Awesomplete

Awesomplete is a simple and lightweight widget with no dependencies. By default the library expects the list of suggestions to be passed as a data attribute, but you can easily hook it up to your back-end with a simple AJAX request.


timeago

Timeago

Timeago is a jQuery plugin that makes it easy to support automatically updating fuzzy timestamps. You cantake full advantageof page caching in your web applications, because the timestamps aren’t calculated on the server.


ramjet

Ramjet

Ramjet is a JavaScript library which helps you make animations transforming one element into another. It supports images and GIFs so that you can build the perfect landing page. You can also use an easing function to make the transformation seem more natural.


patternizer

Patternizer

Patternizer is an online tool that helps you generate patterns. After you choose options like opacity and width, just copy the code that the website gives you and paste it into your stylesheet.


masonry

Masonry

Masonry is a jQuery plugin for building grid layouts. It places elements optimally depending on their sizes to make maximum use of the available space. With a lot of loading effects and options you can customize the look of your page.


lettering

Lettering.js

Lettering is a jQuery plugin that gives you the ability to style every letter, word and line in your text. The best use case is to create typographical CSS3 posters with unique styling for every letter. Text remains fully selectable.


nativefier

NativeFier

Nativefier is a command line Node.js utility which can easily create a desktop application out of any web site. Apps are wrapped in an Electron shell and packaged into an OS executable (.app, .exe, etc.) for use on Windows, OSX and Linux.


lightGallery

Lightgallery

Lightgallery is a responsive gallery plugin for jQuery. It has numerous options and animations which allows you to customise the plugin easily. The video module allows you to create beautiful youtube/vimeo video galleries with automatic thumbnail fetching.


magic animations

Magic Animations

Magic animations is a CSS library for animations. It has a lot of animation types and is easy to use. Just add the stylesheet to your page and set class names to your elements. If you are interested in CSS animations you can also check Animate.css.


bulma

Bulma

Bulma is a modern CSS framework based on the Flexbox layout model. It has a simple grid system, responsive nav bars and versatile media objects. Most Bulma elements can be customized by applying modifier classes.


ColorZilla

This is an extension for Google Chrome that bundles together a big array of features, including a color picker, CSS gradient generator, recent history of used colors, and more. Another similar tool is the open-source extension Eye Dropper.


WhatFont

With WhatFont you can quickly find out which fonts have been used in a webpage. Simply hover on any text, and the extension will show you the name of that typeface. WhatFont also detects the services used for providing the web fonts.


PerfectPixel

PerfectPixel is a Google Chrome extension that allows you to put a semi-transparent image overlay over the top of the developed HTML and perform per pixel comparison between them. It’s a great helper when you want to transform a PSD to HTML flawlessly.


FireShot

Fireshot allows Chrome users to make full web page screenshots and then directly upload, print or send them to Photoshop or the clipboard. It also support an array of popular formats such as pdf, png and gif, and can work offline without a problem.


Blur

Blur is a Google Chrome extension that makes it easy to keep track of and secure all your personal information online. It helps you remember your passwords, generate hard-to-crack new ones, and sync all the browsers and devices you log on.

Source:: Tutorialzine.com

JavaScript fatigue fatigue

By Axel Rauschmayer

Enough with the fatigue – tips against feeling overwhelmed:

  • Don’t try to know everything – it’s impossible in modern web development. Given that there is always more to know, it doesn’t matter that much what you learn (unless you have a specific need).
    • Go for depth in areas you love.
    • Go for breadth and on-demand learning in areas you are merely interested in or think you should know more about.
  • Wait for the critical mass. You can often afford to get started by reading the opinions of people you trust and wait it out until new ideas prove themselves.
  • Stick to things you understand: don’t use more than 1–2 new technologies per project.
    • It’s important to retain at least some feeling of control.
    • Every technology that people need to learn before they can use your project raises the barrier of entry and makes it more difficult to find collaborators, colleagues and employees.
  • Do exploratory toy projects: I like creating small projects that explore technologies or aspects of technologies.
  • Diversify in life: Specializing is good, but it’s also good to have regular activities not related to tech and/or brain. The advantage is that if you are frustrated in one area of your life, you have others to fall back on.

Even with the last of the previous tips, I find it important to remain human. Don’t overdo discipline, don’t become a life improvement machine. Periods of boredom and doing nothing are important for recuperating and inspiration.

When in doubt about what to learn next, you can always go back to fundamentals:

  • JavaScript, CSS, etc. (which technologies are fundamental depends on your work)
  • Non-technological skills: time management, social skills (communication, team building, …), health (posture, moving well, eating well, …), management processes and so on.

Source:: 2ality

Quick Tip: The Easiest Way To Make Responsive Headers

By Danny Markov

quick-tip-responsive-headers

Making pretty, responsive, headers is always a tricky process. Until now you needed to use floats or other complicated tricks and you even had to manually adjust pixel values. But not any more!

The technique we are about to show you relies on the powerful flexbox layout mode to do all the dirty work for you. It uses just a handful of CSS properties to create a header that is properly aligned and looks good on all screen sizes, while leaving the code cleaner and less hacky.

The Technique

In our demonstrative example we’ve built a header, which is separated in three sections with typical header content nested within them:

  • Left section – The company logo.
  • Middle section – Various hyperlinks.
  • Right section – A button.

Below you can check out a simplified version of the code.

In the first tab is the HTML where we group the sections in separate div tags. This makes it easier for CSS rules to be applied and generally produces a more organised code.

In the other tab is the CSS, which is just a couple of lines, does the entire job of finding the right places for the each of the sections.

Click the Run button to open up a live demo. You can test the responsiveness by resizing the frame:

<header>
	<div class="header-left">CoolLogo</div>
	<div class="header-center">
		<ul>
			<li><a href="#">Our products</a></li>
			<li><a href="#">Pricing</a></li>
			<li><a href="#">Blog</a></li>
		</ul>
	</div>
	<div class="header-right"><button>Buy now</button></div>
</header>
header{
	/* Enable flex mode. */
	display: flex; 
	
	/* Spread out the elements inside the header. */
	justify-content: space-between;

	/* Align items vertically in the center. */
	align-items: center;
}
<!DOCTYPE html>
<html>
<head>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Easiest Way To Make Responsive Headers</title>
<link href='https://fonts.googleapis.com/css?family=Fugaz+One' rel='stylesheet' type='text/css'>

<style>
*{
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}

body{
	font: normal 16px sans-serif;
	padding: 0 10%;
	background: #eee;
}

body .container{
	max-width:1200px;
	margin:0 auto;
}

/*	Header	*/

header{
	/* Enable flex mode. */
	display: flex; 
	/* Spread out the elements inside the header. */
	justify-content: space-between;
	/* Align items vertically in the center. */
	align-items: center;

	padding: 40px 100px;
	color: #fff;
	background-color: #488EAD;
}

.header-left{
	font: normal 28px 'Fugaz One', cursive;
}

.header-left span{
	color: #EAD314;
}

.header-center ul{
	list-style: none;
}

.header-center ul li{
	display: inline-block;
	margin: 0 15px;
}

.header-center ul li a{
	text-decoration: none;
	color: #fff;
	cursor: pointer;
	font-weight: bold;
}

.header-right button{
    color: #fff;
    cursor: pointer;
    font-weight: 800;
    text-transform: uppercase;
    padding: 12px 30px;
    border: 2px solid #FFFFFF;
    border-radius: 4px;
    background-color: transparent;
}

.header-right button:hover {
    background-color: rgba(255,255,255,0.1);
}

/*	Main content	*/

.main-content{
	padding: 60px 100px;
	background-color: #fff;
    line-height: 1.5;
    color: #444;
}

.main-content h2{
	margin-bottom: 38px;
}

.main-content p{
	margin: 30px 0;
}


.main-content .placeholder{
	margin: 40px 0;
	height:380px;
	background-color: #e3e3e3;
}


/*	Media queries	*/

@media (max-width: 1200px){
	header{
		padding: 40px 60px;
	}

	.main-content{
		padding: 100px 60px;
	}

	body {
	    padding: 0 5%;
	}
}

@media (max-width: 1000px){
	header{
		/* Reverse the axis of the header, making it vertical. */
		flex-direction: column;
		/* Align items to the begining (the left) of the header. */
		align-items: flex-start;
	}

	header > div{
		margin: 12px 0;
	}

	.header-center ul li{
		margin: 0 15px 0 0;
	}

}

@media (max-width: 600px){
	body {
	    padding: 0 10px;
	}

	.header-left{
		margin-top:0;
	}

	header {
	    padding: 30px;
	}

	.main-content{
		padding:30px;
	}
}


</style>
</head>
<body>

<div class="container">
	
	<header>
		<div class="header-left"><span>Cool</span>Logo</div>
		<div class="header-center">
			<ul>
				<li><a href="#">Our products</a></li>
				<li><a href="#">Pricing</a></li>
				<li><a href="#">Blog</a></li>
			</ul>
		</div>
		<div class="header-right"><button>Buy now</button></div>
	</header>

	<section class="main-content">
		<h2>Header with three justify aligned sections</h2>
		<p>Using the power of flexbox, the logo, links, and button of our header stay in their designated places, no matter the screen size. The <strong style="white-space: nowrap;">justify-content</strong> property offers a clean approach and allows us to align the section of the header without a hassle. No need for any floats, margins or crazy width calculations.</p>
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus at congue urna, pellentesque faucibus justo. Integer a lorem a mauris suscipit congue luctus ut quam. Mauris pellentesque pellentesque mattis. In sed mi dignissim, faucibus elit at, rutrum odio. Mauris et velit magna. Maecenas iaculis eget sapien eu gravida. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum a egestas magna. Aenean tellus elit, aliquet at lacinia at, accumsan eget neque. Maecenas rutrum risus quis sem scelerisque sagittis. Quisque sit amet turpis lorem. </p>
		<div class="placeholder"></div>
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus at congue urna, pellentesque faucibus justo. Integer a lorem a mauris suscipit congue luctus ut quam. Mauris pellentesque pellentesque mattis. In sed mi dignissim, faucibus elit at, rutrum odio. Mauris et velit magna. Maecenas iaculis eget sapien eu gravida. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum a egestas magna. Aenean tellus elit, aliquet at lacinia at, accumsan eget neque. Maecenas rutrum risus quis sem scelerisque sagittis. Quisque sit amet turpis lorem. </p>
	</section>

</div>

</body>
</html>

Full responsiveness

The space-between trick will always take care of the alignment, even when the screen size changes. However, when the viewport becomes too small for a horizontal header, we can make it go vertical by changing the flex-direction property in a media query.

@media (max-width: 1000px){
	header{
		/* Reverse the axis of the header, making it vertical. */
		flex-direction: column;
		
		/* Align items to the begining (the left) of the header. */
		align-items: flex-start;
	}
}

Conclusion

This sums up our quick tutorial! We hope you found it useful and will start applying it right away. Flexbox has pretty good browser support nowadays, so unless your user base is IE heavy, this technique can be applied without causing any mayhem.

To learn more about flexbox and the CSS properties that we used, check out these links:

Source:: Tutorialzine.com

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

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

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

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