Monthly Archives: December 2015

The future of bundling JavaScript modules

By Axel Rauschmayer

This blog post examines how the bundling of modules is affected by two future developments: HTTP/2 and native modules.

Why we bundle modules

Bundling modules means combining several files with modules into a single file. That is done for three reasons:

  1. Less files need to be retrieved in order to load all modules.
  2. Compressing the bundled file is slightly more efficient than compressing separate files.
  3. During bundling, unused exports can be removed, potentially resulting in significant space savings.

JavaScript modules

With ECMAScript 6, JavaScript finally got built-in modules (I’m calling them JavaScript modules for the remainder of this blog post). However, that feature is currently in a strange position:

On one hand, ES6 fully standardized their syntax and much of their semantics. They have become a popular format for writing modules and their static structure enables the automatic omission of unused exports (also known as “tree-shaking” in the JavaScript world).

On the other hand, standardizing how to load JavaScript modules is ongoing and no JavaScript engine supports them natively, yet. That means that, at the moment, the only way of using JavaScript modules is by compiling them to a non-native format. Popular solutions are: browserify, webpack, jspm and Rollup.

Future developments and bundling

Let’s look at two future developments and how they affect the bundling of JavaScript modules.

Future development: HTTP/2

HTTP/2 is slowly being rolled out. It mainly affects reason #2 for bundling: With HTTP/1, you need one connection per file you are requesting. With HTTP/2, you can retrieve multiple files per connection, which means that there are no performance gains if you download multiple files instead of a single one. That enables smaller, more incremental updates: With bundling, you always need to download the complete bundle. Without bundling, you only need to download the parts that have changed (while the other parts are often still in the browser cache).

However, reasons #2 and #3 for bundling are not negated by HTTP/2. Therefore, mixed approaches may be adopted in the future, to optimize for both incremental updates and minimal total download size.

Future development: native JavaScript modules

Once engines support native JavaScript modules, will that affect bundling? Even AMD modules – which run natively in browsers – have a custom bundle format (along with a minimal loader). Will native JS modules be different? It looks like they will. Rollup lets you bundle multiple JS modules into a single JS module.

Take, for example, these two JS modules:

    // lib.js
    export function foo() {}
    export function bar() {}
    
    // main.js
    import {foo} from './lib.js';
    console.log(foo());

Rollup can bundle these two JS modules into the following single JS module (not the eliminated unused export bar):

    function foo() {}
    
    console.log(foo());

Rollup’s site has a nice interactive playground where you can try it out. It wasn’t a given that that would work – quoting Rollup’s creator Rich Harris:

When I started writing Rollup, it was an experiment that I wasn’t certain would succeed.

The way imports are handled by JS modules helps with bundling: they are not copies of exports, they are read-only views on them.

Further reading

  • Building for HTTP/2” by Rebecca Murphey (explains how best practices change – often radically – with this new version of HTTP)
  • Chap. “Modules” in “Exploring ES6” (explains how ES6 modules work)
  • Babel and CommonJS modules” (explains how Babel ensures that transpiled ES6 modules interoperate properly with CommonJS modules)

Source:: 2ality

Tree-shaking with webpack 2 and Babel 6

By Axel Rauschmayer

Rich Harris’ module bundler Rollup pioneered a new feature in JavaScript world: tree-shaking, excluding unused exports from bundles. Rollup depends on the static structure of ES6 modules (imports and exports can’t be changed at runtime) to detect which exports are unused.

Tree-shaking for webpack is currently in beta. This blog post explains how it works. The project we are going to examine is on GitHub: tree-shaking-demo

How webpack 2 eliminates unused exports

webpack 2, a new version that is in beta, eliminates unused exports in two steps:

  • First, all ES6 module files are combined into a single bundle file. In that file, exports that were not imported anywhere are not exported, anymore.

  • Second, the bundle is minified, while eliminating dead code. Therefore, entities that are neither exported nor used inside their modules do not appear in the minified bundle. Without the first step, dead code elimination would never remove exports (registering an export keeps it alive).

Unused exports can only be reliably detected at build time if the module system has a static structure. Therefore, webpack 2 can parse and understand all of ES6 and only tree-shakes if it detects an ES6 module. However, only imports and exports are transpiled to ES5. If you want all of the bundle to be in ES5, you need a transpiler for the remaining parts of ES6. In this blog post, we’ll use Babel 6.

Input: ES6 code

The demo project has two ES6 modules.

helpers.js with helper functions:

    // helpers.js
    export function foo() {
        return 'foo';
    }
    export function bar() {
        return 'bar';
    }

main.js, the entry point of the web application:

    // main.js
    import 'babel-polyfill';
    import {foo} from './helpers';
    
    let elem = document.getElementById('output');
    elem.innerHTML = `Output: ${foo()}`;

Note that the export bar of module helpers is not used anywhere in this project.

Output without tree-shaking

The canonical choice for Babel 6 is to use the preset es2015:

    {
        presets: ['es2015'],
    }

However, that preset includes the plugin transform-es2015-modules-commonjs, which means that Babel will output CommonJS modules and webpack won’t be able to tree-shake:

    function(module, exports) {
    
        'use strict';
    
        Object.defineProperty(exports, "__esModule", {
            value: true
        });
        exports.foo = foo;
        exports.bar = bar;
        function foo() {
            return 'foo';
        }
        function bar() {
            return 'bar';
        }
    
    }

You can see that bar is part of the exports, which prevents it being recognized as dead code by minification.

Output with tree-shaking

What we want is Babel’s es2015, but without the plugin transform-es2015-modules-commonjs. At the moment, the only way to get that is by mentioning all of the preset’s plugins in your configuration data, except for the one we want to exclude. The preset’s source is on GitHub, so it’s basically a copy/paste task:

    {
        plugins: [
            'transform-es2015-template-literals',
            'transform-es2015-literals',
            'transform-es2015-function-name',
            'transform-es2015-arrow-functions',
            'transform-es2015-block-scoped-functions',
            'transform-es2015-classes',
            'transform-es2015-object-super',
            'transform-es2015-shorthand-properties',
            'transform-es2015-computed-properties',
            'transform-es2015-for-of',
            'transform-es2015-sticky-regex',
            'transform-es2015-unicode-regex',
            'check-es2015-constants',
            'transform-es2015-spread',
            'transform-es2015-parameters',
            'transform-es2015-destructuring',
            'transform-es2015-block-scoping',
            'transform-es2015-typeof-symbol',
            ['transform-regenerator', { async: false, asyncGenerators: false }],
        ],
    }

If we build the project now, module helpers looks like this inside the bundle:

    function(module, exports, __webpack_require__) {
    
        /* harmony export */ exports["foo"] = foo;
        /* unused harmony export bar */;
    
        function foo() {
            return 'foo';
        }
        function bar() {
            return 'bar';
        }
    }

Only foo is an export now, but bar is still there. After minification, helpers looks like this (I’ve added line breaks and whitespace to make the code easier to read):

    function (t, n, r) {
        function e() {
            return "foo"
        }
    
        n.foo = e
    }

Et voilà – no more function bar!

Further reading

Source:: 2ality

Installing past or future versions of npm packages

By Axel Rauschmayer

npm lets you install versions of packages other than the current one, via:

    npm install "package-name»@"tag»
    npm install "package-name»@"version»

Installing tags

Tags are aliases for versions. You can look up available tags via:

    npm view "package-name» dist-tags

Example:

    $ npm view webpack dist-tags
    { latest: '1.12.9', beta: '2.0.1-beta' }

Installing versions

You can look up available versions via:

    npm view "package-name» versions

Example:

    $ npm view webpack versions
    
    [ '0.1.0',
      '0.1.1',
      ···
      '1.12.8',
      '1.12.9',
      '2.0.0-beta',
      '2.0.1-beta' ]

Source:: 2ality

Why is (0,obj.prop)() not a method call?

By Axel Rauschmayer

This blog post explores references, a mechanism used by the spec to explain the difference between the following two expressions:

    obj.prop()
    (0, obj.prop)()

Method calls versus function calls

Consider the following object:

    var obj = {
        getThis: function () {
            "use strict";
            return this;
        },
    };

If you call obj.getThis, you have a method call (this points to the object in which the method is stored):

    > obj.getThis() === obj
    true

If you store obj.getThis in a variable and then call it, you are making a function call:

    > var func = obj.getThis;
    > func()
    undefined

The effect is the same if you use the comma operator. Quick recap: the comma operator works like this:

    (expr1, expr2) === expr2

That is, both expressions are evaluated, the result of the whole expression is expr2.

If you apply the comma operator to obj.getThis before calling it, you are also making a function call:

    > (0,obj.getThis)()
    undefined

What the first operand is doesn’t matter at all, here, I use 0, because its short. I’d expect many JavaScript engines to optimize and eliminate the evaluation of the first operand.

However, only using parentheses does not change anything:

    > (obj.getThis)() === obj
    true

So what is going on? The answer has to do with references.

References, a data structure of the ECMAScript spec

References are a data structure that is used internally by the ECMAScript language specification. A reference has three components:

  1. Base value: is either undefined, a primitive value, an object or an environment record. undefined means that a variable name could not be resolved. Accessed via GetBase(V) (given a reference V).
  2. Referenced name: is a string or a symbol. Accessed via GetReferencedName(V) (given a reference V).
  3. Strict reference: flag indicating whether or not the reference was created in strict mode. Accessed via IsStrictReference(V) (given a reference V).

Examples of JavaScript expressions that produce references:

  • Property reference: Evaluating obj.prop in strict mode produces the reference (obj, 'prop', true).
  • Identifier reference: Evaluating foo in strict mode produces the reference (env, 'foo', true). env is the environment record where the variable foo is stored.

The flag for strict mode is necessary, because some operations cause an exception in strict mode, but fail silently in sloppy mode. For example: setting an unresolved variable in sloppy mode creates a global variable, setting it in strict mode throws a ReferenceError.

These are two operations (of several) for references:

  • GetValue(V) if V is a value, the result is V. If V is a reference, the result is the value pointed to by the reference. This conversion from reference to referenced value is called dereferencing.
  • PutValue (V, W) writes the value W to the reference V.
  • GetThisValue(V) is only called if V is a property reference. For normal references, it returns the base value. For references created via super, it returns the additional component thisValue that they have ((which is needed for super property references)[http://exploringjs.com/es6/ch_classes.html#super-properties]).

References in the example

We are now ready to understand the examples we looked at earlier.

The following expression produces a reference:

    obj.getThis

If you function-call this reference V then this is set to GetThisValue(V).

If you wrap obj.getThis in parentheses, nothing changes, parentheses only syntactically group things, but the don’t influence how something is evaluated. That is, the result of the following expression is still a reference:

    (obj.getThis)

If, however, you assign the reference returned by obj.getThis to a variable, the reference is dereferenced:

    var func = obj.getThis;

In other words: what is stored in func is a function, not a reference. In the language spec, assignment operators use GetValue() to turn references into values.

The comma operator also dereferences its operands. Consider this expression:

    (0, obj.getThis)

The comma operator`) to ensure that the result of each operand is dereferenced if it is a reference.

References and bind()

References only being temporary is also the reason why you need to use bind if you want to turn a method into a callback (first line):

    var log = console.log.bind(console);
    log('hello');

If you simply did:

    var log = console.log;

Then the receiver (this) would get lost, because console.log is dereferenced before it is stored in log.

Why does the ECMAScript language specification use references?

JavaScript engines, which are implementations of the ECMAScript language specification, don’t actually use references. That means that they are a device that helps with writing the spec. To see why, consider that they represent storage locations. Then consider that all of the following operations work with storage locations:

  • Reading a value:

        x
        obj.prop
        super.prop
        obj["prop"]
    
  • Calling a function or a method:

        x()
        obj.prop()
        super.prop()
        obj["prop"]()
    
  • Assigning a value:

        x = 123
        obj.prop = 123
        super.prop = 123
        obj["prop"] = 123
    
  • Compound assignment operators. For example, the addition assignment operator (+=):

        x += 5
        obj.prop += 5
        super.prop += 5
        obj["prop"] += 5
    
  • typeof:

        typeof x
        typeof obj.prop
        typeof super.prop
        typeof obj["prop"]
    
  • delete:

        delete x
        delete obj.prop
        delete super.prop
        delete obj["prop"]
    

Because each storage location is represented by the same construct, a reference, the specification only needs to describe a single version of each operation instead of several versions (e.g.: delete for a variable, delete for a property with a fixed key, delete for a property with a dynamically computed key, etc.).

Conclusion

You don’t actually see references when you use JavaScript. But there are languages (e.g. Common Lisp) where references are first class values. That enables intriguing applications. You can, for example, implement functions that perform an assignment for you.

Source:: 2ality

Creating Your First Desktop App With HTML, JS and Electron

By Danny Markov

creating-your-first-desktop-app-with-electron

Web applications become more and more powerful every year, but there is still room for desktop apps with full access to the hardware of your computer. Today you can create desktop apps using the already familiar HTML, JS and Node.js, then package it into an executable file and distribute it accordingly across Windows, OS X and Linux.

There are two popular open source projects which make this possible. These are NW.js, which we covered a few months ago, and the newer Electron, which we are going to use today (see the differences between them here). We are going to rewrite the older NW.js version to use Electron, so you can easily compare them.

Getting Started With Electron

Apps built with Electron are just web sites which are opened in an embedded Chromium web browser. In addition to the regular HTML5 APIs, these websites can use the full suite of Node.js modules and special Electron modules which give access to the operating system.

For the sake of this tutorial, we will be building a simple app that fetches the most recent Tutorialzine articles via our RSS feed and displays them in a cool looking carousel. All the files needed for the app to work are available in an archive which you can get from the Download button near the top of the page.

Extract its contents in a directory of your choice. Judging by the file structure, you would never guess this is a desktop application and not just a simple website.

Directory Structure

We will take a closer look at the more interesting files and how it all works in a minute, but first, let’s take the app for a spin.

Running the App

Since an Electron app is just a fancy Node.js app, you will need to have npm installed. You can learn how to do it here, it’s pretty straightforward.

Once you’ve got that covered, open a new cmd or terminal in the directory with the extracted files and run this command:

npm install

This will create a node_modules folder containing all the Node.js dependencies required for the app to work. Everything should be good to go now, in the same terminal as before enter the following:

npm start

The app should open up in it’s own window. Notice it has a top menu bar and everything!

Electron App In Action

Electron App In Action

You’ve probably noticed that starting the app isn’t too user friendly. However, this is just the developer’s way of running an Electron app. When packaged for the public, the it will be installed like a normal program and opened like one, just by double clicking on its icon.

How it’s made

Here, we will talk about the most essential files in any electron app. Let’s start with package.json, which holds various information about the project, such as the version, npm dependencies and other important settings.

package.json

{
  "name": "electron-app",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "dependencies": {
    "pretty-bytes": "^2.0.1"
  },
  "devDependencies": {
    "electron-prebuilt": "^0.35.2"
  },
  "scripts": {
    "start": "electron main.js"
  },
  "author": "",
  "license": "ISC"
}

If you’ve worked with node.js before, you already know how this works. The most significant thing to note here is the scripts property, where we’ve defined the npm start command, allowing us to run the app like we did earlier. When we call it, we ask electron to run the main.js file. This JS file contains a short script that opens the app window, and defines some options and event handlers.

main.js

var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform != 'darwin') {
        app.quit();
    }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
    // Create the browser window.
    mainWindow = new BrowserWindow({width: 900, height: 600});

    // and load the index.html of the app.
    mainWindow.loadURL('file://' + __dirname + '/index.html');

    // Emitted when the window is closed.
    mainWindow.on('closed', function() {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null;
    });
});

Take a look at what we do in the ‘ready’ method. First we define a browser window and set it’s initial size. Then, we load the index.html file in it, which works similarly to opening a HTML file in your browser.

As you will see, the HTML file itself is nothing special – a container for the carousel and a paragraph were CPU and RAM stats are displayed.

index.html

<!DOCTYPE html>
<html>
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Tutorialzine Electron Experiment</title>

    <link rel="stylesheet" href="./css/jquery.flipster.min.css">
    <link rel="stylesheet" href="./css/styles.css">

</head>
<body>

<div class="flipster">
    <ul>
    </ul>
</div>

<p class="stats"></p>

<!-->In Electron, this is the correct way to include jQuery<-->
<script>window.$ = window.jQuery = require('./js/jquery.min.js');</script>
<script src="./js/jquery.flipster.min.js"></script>
<script src="./js/script.js"></script>
</body>
</html>

The HTML also links to the needed stylesheets, JS libraries and scripts. Notice that jQuery is included in a weird way. See this issue for more information about that.

Finally, here is the actual JavaScript for the app. In it we access Tutorialzine’s RSS feed, fetch recent articles and display them. If we try to do this in a browser environment, it won’t work, because the RSS feed is located on a different domain and fetching from it is forbidden. In Electron, however, this limitation doesn’t apply and we can simply get the needed information with an AJAX request.

$(function(){

    // Display some statistics about this computer, using node's os module.

    var os = require('os');
    var prettyBytes = require('pretty-bytes');

    $('.stats').append('Number of cpu cores: <span>' + os.cpus().length + '</span>');
    $('.stats').append('Free memory: <span>' + prettyBytes(os.freemem())+ '</span>');

    // Electron's UI library. We will need it for later.

    var shell = require('shell');


    // Fetch the recent posts on Tutorialzine.

    var ul = $('.flipster ul');

    // The same-origin security policy doesn't apply to electron, so we can
    // send ajax request to other sites. Let's fetch Tutorialzine's rss feed:

    $.get('http://feeds.feedburner.com/Tutorialzine', function(response){

        var rss = $(response);

        // Find all articles in the RSS feed:

        rss.find('item').each(function(){
            var item = $(this);

            var content = item.find('encoded').html().split('</a></div>')[0]+'</a></div>';
            var urlRegex = /(http|ftp|https)://[w-_]+(.[w-_]+)+([w-.,@?^=%&amp;:/~+#]*[w-@?^=%&amp;/~+#])?/g;

            // Fetch the first image of the article.
            var imageSource = content.match(urlRegex)[1];


            // Create a li item for every article, and append it to the unordered list.

            var li = $('<li><img /><a target="_blank"></a></li>');

            li.find('a')
                .attr('href', item.find('link').text())
                .text(item.find("title").text());

            li.find('img').attr('src', imageSource);

            li.appendTo(ul);

        });

        // Initialize the flipster plugin.

        $('.flipster').flipster({
            style: 'carousel'
        });

        // When an article is clicked, open the page in the system default browser.
        // Otherwise it would open it in the electron window which is not what we want.

        $('.flipster').on('click', 'a', function (e) {

            e.preventDefault();

            // Open URL with default browser.

            shell.openExternal(e.target.href);

        });

    });

});

A cool thing about the above code, is that in one file we simultaneously use:

  • JavaScript libraries – jQuery and jQuery Flipster to make the carousel.
  • Electron native modules – Shell which provides APIs for desktop related tasks, in our case opening a URL in the default web browser.
  • Node.js modules – OS for accessing system memory information, Pretty Bytes for formatting.

And with this our app is ready!

Packaging and Distribution

There is one other important thing to do to make your app ready for end users. You need to package it into an executable that can be started with a double click on users’ machines. Since Electron apps can work on multiple operating systems and every OS is different, there need to be separate distributions for Windows, for OS X and for Linux. Tools such as this npm module are a good place to start – Electron Packager.

Take into consideration that the packaging takes all your assets, all the required node.js modules, plus a minified WebKit browser and places them together in a single executable file. All these things sum up and the final result is an app that is roughly 50mb in size. This is quite a lot and isn’t practical for a simple app like our example here, but this becomes irrelevant when we work with big, complex applications.

Conclusion

The only major difference with NW.js that you will see in our example is that NW.js opens an HTML page directly, whereas Electron starts up by executing a JavaScript file and you create an application window through code. Electron’s way gives you more control, as you can easily build multi-window applications and organize the communication between them.

Overall Electron is an exciting way to build desktop web applications using web technologies. Here is what you should read next:

Source:: Tutorialzine.com

Babel and CommonJS modules

By Axel Rauschmayer

This blog post examines how Babel ensures that code it transpiles interoperates properly with normal CommonJS modules. Consult chapter “Modules” in “Exploring ES6” for more information on ES6 modules.

Starting point for this series of posts on Babel:Configuring Babel 6

ES6 modules vs. CommonJS modules

ECMAScript 6 modules

Default export (single export):

    // lib.js
    export default function () {}
    
    // main.js
    import lib from './lib';

Named exports (multiple exports):

    // lib.js
    export function foo() {}
    export function bar() {}
    
    // main1.js
    import * as lib from './lib';
    lib.foo();
    lib.bar();
    // main2.js
    import {foo, bar} from './lib';
    foo();
    bar();

It is possible to combine both styles of exports, they don’t conflict with each other.

CommonJS modules

Single export:

    // lib.js
    module.exports = function () {};
    
    // main.js
    var lib = require('./lib');

Multiple exports:

    // lib.js
    exports.foo = function () {};
    exports.bar = function () {};
    
    // main1.js
    var lib = require('./lib');
    lib.foo();
    lib.bar();
    // main2.js
    var foo = require('./lib').foo;
    var bar = require('./lib').bar;
    foo();
    bar();

Single exports and multiple exports are mutually exclusive. You have to use either one the two styles. Some modules combine both styles as follows:

    function defaultExport() {}
    defaultExport.foo = function () {};
    defaultExport.bar = function () {};
    
    module.exports = defaultExport;

Comparing the two modules formats

ES6 modules have two advantages over CommonJS modules.

First, their rigid structure makes them statically analyzable. That enables, e.g., tree shaking (dead code elimination) which can significantly reduce the size of bundled modules.

Second, imports are never accessed directly, which means that cyclic dependencies are always supported. In CommonJS, you must code like this, so that the exported entity foo can be filled in later:

    var lib = require('./lib');
    lib.foo();

In contrast, this style of importing does not work (neither do single exports via module.exports):

    var foo = require('./lib').foo;
    foo();

More information on cyclic dependencies: Section “Support for cyclic dependencies” in “Exploring ES6”.

How Babel compiles ES6 modules to CommonJS

As an example, consider the following ES6 module.

    export function foo() {};
    export default 123;

Babel transpiles this to the following CommonJS code:

    "use strict";
    
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.foo = foo;
    function foo() {};
    exports.default = 123;

The following subsections answer questions you may have about this code:

  • Why isn’t the default export done like a CommonJS single export?
  • Why mark transpiled ES6 modules with the flag __esModule?

Why isn’t the default export done like a CommonJS single export?

Answer: There are three reasons for doing so.

First, it is closer to ES6 semantics.

Second, you prevent scenarios like the following.

    // lib.js
    export default {
        foo: () => {},
        bar: () => {},
    };
    // main.js
    import {foo,bar} from './lib';

This is illegal in native ES6 and Babel shouldn’t let you do that.

Third, you want to support doing a default export and named exports at the same time. You could treat a module with just a default export like a single-export CommonJS module:

    // lib_es6.js
    export default 'abc';
    // main_cjs.js
    var lib = require('./lib_es6');
        // 'abc'

However, then the exports would change completely if you add a named export:

    // lib_es6.js
    export default 'abc';
    export var foo = 123;
    // main_cjs.js
    var lib = require('./lib_es6');
        // { foo: 123, default: 'abc' }

Why mark transpiled ES6 modules with the flag __esModule?

The flag enables Babel to treat non-ES6 CommonJS modules that have single exports as if they were ES6 modules with default exports. How that is done is examined in the next section.

How Babel imports CommonJS modules

Default imports

This ES6 code:

    import assert from 'assert';
    assert(true);

is compiled to this ES5 code:

    'use strict';
    
    function _interopRequireDefault(obj) {
        return obj && obj.__esModule
            ? obj
            : { 'default': obj };
    }
    
    var _assert = require('assert');
    var _assert2 = _interopRequireDefault(_assert);
    
    (0, _assert2['default'])(true); // (A)

Explanations:

  • _interopRequireDefault(): An ES6 CommonJS module is used as is (if it has a default export then it has a property named default). A normal CommonJS module becomes the value of the property default. In other words, in the later case, the module’s exports become the default export.

  • Note that the default export is always accessed via the exports object _assert2 (line A), never directly, like this:

        var assert = _assert2.default;
    

    The reason for that is support for cyclic dependencies.

  • (0, _assert2['default']) is done so that the invocation in line A is a function call, not a method call (with this === _assert2).

Namespace imports

This ES6 code:

    import * as assert from 'assert';
    assert.ok(true);

is compiled to this ES5 code:

    'use strict';
    
    function _interopRequireWildcard(obj) {
        if (obj && obj.__esModule) {
            return obj;
        }
        else {
            var newObj = {}; // (A)
            if (obj != null) {
                for (var key in obj) {
                    if (Object.prototype.hasOwnProperty.call(obj, key))
                        newObj[key] = obj[key];
                }
            }
            newObj.default = obj;
            return newObj;
        }
    }
    
    var _assert = require('assert');
    var assert = _interopRequireWildcard(_assert);
    
    assert.ok(true);

Explanations:

  • _interopRequireWildcard(): CommonJS exports are translated to an object where the named exports are the properties of the exports objects and the default exports is (yet again) the exports object. The module assert is an example of where a normal CommonJS module mixes a single export with multiple exports and the Babel work-around translates such a module to the world of ES6:

        import assert, {ok} from `assert`;
    

    assert accesses a default export, {ok} accesses a named export.

  • Babel creates a new object (line A), because it must not modify the original exports object.

Named imports

This ES6 code:

    import {ok} from 'assert';
    
    ok();

is compiled to this ES5 code:

    'use strict';
    
    var _assert = require('assert');
    
    (0, _assert.ok)();

Again, you can see that ok() is never accessed directly, always via _assert, which ensures that cyclic dependencies work.

Recommendations

You need to look very closely at what a module exports and then choose the appropriate way of importing. For example, conceptually, the Node.js module fs is clearly a collection of named exports, not a single export (an object). Therefore, while both of the following two ways of importing this module work, the second one is the better choice.

    import fs from 'fs'; // no
    import * as fs from 'fs'; // recommended

If you want to future-proof your normal CommonJS module, you should opt for either a single export or multiple named exports, but not for mixing styles (attaching named exports as properties of a single export).

Source:: 2ality

Babel 6: loose mode

By Axel Rauschmayer

Babel’s loose mode transpiles ES6 code to ES5 code that is less faithful to ES6 semantics. This blog post explains how that works and what the pros and cons are (spoiler: normally not recommended).

Starting point for this series of posts on Babel 6:Configuring Babel 6” [explains the basics: configuration files, presets, plugins, etc.]

Two modes

Many plugins in Babel have two modes:

  • A normal mode follows the semantics of ECMAScript 6 as closely as possible.
  • A loose mode produces simpler ES5 code.

Normally, it is recommended to not use loose mode. The pros and cons are:

  • Pros: The generated code is potentially faster and more compatible with older engines. It also tends to be cleaner, more “ES5-style”.
  • Con: You risk getting problems later on, when you switch from transpiled ES6 to native ES6. That is rarely a risk worth taking.

Switching on loose mode

The preset es2015-loose is the loose version of the standard ES6 preset, es2015. The preset’s code provides a good overview of what plugins have a loose mode and how to switch it on. This is an excerpt:

    module.exports = {
      plugins: [
        ···
        [require("babel-plugin-transform-es2015-classes"), {loose: true}],
        require("babel-plugin-transform-es2015-object-super"),
        ···
      ]
    };

This is an ES5 CommonJS module. If you configure Babel via .babelrc or package.json (details), you need to use JSON, like this:

    ···
    "plugins": [
      ···
      ["transform-es2015-classes", {loose: true}],
      "transform-es2015-object-super",
      ···
    ],
    ···

Example: the output of normal mode and loose mode

Let’s see how the modes affect the transpilation of the following code.

    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
        toString() {
            return `(${this.x}, ${this.y})`;
        }
    }

Normal mode

In normal mode, the prototype methods of the class are added via Object.defineProperty (line A), to ensure that they are non-enumerable, as required by the ES6 spec.

    "use strict";
    
    var _createClass = (function () {
        function defineProperties(target, props) {
            for (var i = 0; i < props.length; i++) {
                var descriptor = props[i];
                descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true;
                if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); // (A)
            }
        }
        return function (Constructor, protoProps, staticProps) {
            if (protoProps) defineProperties(Constructor.prototype, protoProps);
            if (staticProps) defineProperties(Constructor, staticProps);
            return Constructor;
        };
    })();
    
    function _classCallCheck(instance, Constructor) {
        if (!(instance instanceof Constructor)) {
            throw new TypeError("Cannot call a class as a function");
        }
    }
    
    var Point = (function () {
        function Point(x, y) {
            _classCallCheck(this, Point);
    
            this.x = x;
            this.y = y;
        }
    
        _createClass(Point, [{
            key: "toString",
            value: function toString() {
                return "(" + this.x + ", " + this.y + ")";
            }
        }]);
    
        return Point;
    })();

Loose mode

In loose mode, normal assignment is used to add methods (line A). This style is more like you’d hand-write code in ES5.

    "use strict";
    
    function _classCallCheck(instance, Constructor) { ··· }
    
    var Point = (function () {
        function Point(x, y) {
            _classCallCheck(this, Point);
    
            this.x = x;
            this.y = y;
        }
    
        Point.prototype.toString = function toString() { // (A)
            return "(" + this.x + ", " + this.y + ")";
        };
    
        return Point;
    })();

Source:: 2ality

Babel 6: configuring ES6 standard library and helpers

By Axel Rauschmayer

This blog post explains how to configure how Babel 6 accesses its own helper functions and the ES6 standard library.

For more information on how to use Babel’s presets and plugins, consult the blog post “Configuring Babel 6”.

babel-polyfill

This package installs two things into global variables:

  • Whatever is missing from the ES6 runtime library (Map, new string methods, etc.), globally. Provided via core-js.
  • The runtime for Regenerator (which is used by Babel to transpile ES6 generators to ES5).

Install this package via npm as a runtime dependency if you find that anything from these two sources is missing in your transpiled code. In Node.js 5 you may be able to get by without using it, because that version comes with much of the ES6 standard library and native generators.

babel-plugin-external-helpers-2

This package transform the Babel output so that its helpers come from an object in a global variable and are not inserted into each file (possibly redundantly).

Alas, the helpers can only be accessed via a global variable. If you want to access them via a module, you need babel-plugin-transform-runtime. But that plugin also affects how you access the standard library, which may not be what you want.

As an example, consider the following ES6 code, before transpilation:

    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
        toString() {
            return `(${this.x}, ${this.y})`;
        }
    }

If you transpile it with the es2015 preset and without external-helpers-2, you get:

    "use strict";
    
    var _createClass = (function () {
        function defineProperties(target, props) {
            for (var i = 0; i < props.length; i++) {
                var descriptor = props[i];
                descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true;
                if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor);
            }
        }
        return function (Constructor, protoProps, staticProps) {
            if (protoProps) defineProperties(Constructor.prototype, protoProps);
            if (staticProps) defineProperties(Constructor, staticProps);
            return Constructor;
        };
    })();
    
    function _classCallCheck(instance, Constructor) {
        if (!(instance instanceof Constructor)) {
            throw new TypeError("Cannot call a class as a function");
        }
    }
    
    var Point = (function () {
        function Point(x, y) {
            _classCallCheck(this, Point);
    
            this.x = x;
            this.y = y;
        }
    
        _createClass(Point, [{
            key: "toString",
            value: function toString() {
                return "(" + this.x + ", " + this.y + ")";
            }
        }]);
    
        return Point;
    })();

Note the two helper functions _createClass and _classCallCheck.

If you additionally switch on the plugin external-helpers-2, you get this output:

    "use strict";
    
    var Point = (function () {
        function Point(x, y) {
            babelHelpers.classCallCheck(this, Point);
    
            this.x = x;
            this.y = y;
        }
    
        babelHelpers.createClass(Point, [{
            key: "toString",
            value: function toString() {
                return "(" + this.x + ", " + this.y + ")";
            }
        }]);
        return Point;
    })();

Creating a file with the Babel helpers

In order to create a file that sets up the global variable babelHelpers, you need to call the shell command babel-external-helpers (which is installed via the package babel-cli). This command supports three output formats:

  • babel-external-helpers -t global
    prints a Node.js module that puts the helpers into global.babelHelpers.

  • babel-external-helpers -t var
    prints browser code that puts the helpers into the global variable babelHelpers.

  • babel-external-helpers -t umd
    prints a Universal Module Definition (UMD) that works as CommonJS module, AMD module and via a global variable.

This invocation prints usage information:

    babel-external-helpers --help

babel-plugin-transform-runtime

If you install this plugin and switch it on, both helpers and uses of the ES6 standard library are redirected to imports from package babel-runtime (which therefore become a runtime dependency).

Babel helpers

transform-runtime works well for the helpers. The previous ES6 example is transpiled to:

    'use strict';
    
    var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
    
    var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
    
    var _createClass2 = require('babel-runtime/helpers/createClass');
    
    var _createClass3 = _interopRequireDefault(_createClass2);
    
    require('babel-core/external-helpers');
    
    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
    
    var Point = (function () {
        function Point(x, y) {
            (0, _classCallCheck3.default)(this, Point);
    
            this.x = x;
            this.y = y;
        }
    
        (0, _createClass3.default)(Point, [{
            key: 'toString',
            value: function toString() {
                return '(' + this.x + ', ' + this.y + ')';
            }
        }]);
        return Point;
    })();

The helper function _interopRequireDefault ensures that either plain CommonJS modules can be used or transpiled ES6 modules.

ES6 runtime library

However, transform-runtime does not do as well for the ES6 runtime library. Consider, for example, the following ES6 code:

    let map = new Map();
    
    console.log('a'.repeat(3));
    console.log(String.prototype.repeat.call('b', 3));

This becomes:

    'use strict';
    
    var _map = require('babel-runtime/core-js/map');
    
    var _map2 = _interopRequireDefault(_map);
    
    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
    
    var map = new _map2.default();
    
    console.log('a'.repeat(3));
    console.log(String.prototype.repeat.call('b', 3));

That is, new Map() is changed successfully, but method invocations are not detected (doing so is difficult to impossible!).

Thus, manually invoking methods is a better approach:

    import * as core from 'core-js/library';
    console.log(core.String.repeat('c', 3));
    
    import repeat from 'core-js/fn/string/repeat.js';
    console.log(repeat('d', 3));

Source:: 2ality

The Languages And Frameworks You Should Learn In 2016

By Martin Angelov

the-languages-and-frameworks-you-should-learn-in-2016

A lot happened in the software development world in 2015. There were new releases of popular programming languages, new versions of important frameworks and new tools. You will find a short list of the new releases that we think are most important below.

The Trends

In the last few years, there has been a trend towards shifting the business logic of web apps from the backend to the frontend, with the backend being delegated to a simple API. This makes the choice of a frontend framework that much more important.

Another significant advancement for the web as a platform in 2015 was the release of the Edge web browser. This is the successor of Internet Explorer which has an updated interface and faster performance. What sets it apart from IE is that it adopts the same quick release schedule that Firefox and Chrome follow. This is going to move the JavaScript community forward as updates to JavaScript and web standards will be available in weeks rather than years everywhere.


Languages and Platforms

Python 3.5 was released this year with a lot of new features like Asyncio, which gives you a node.js-like event loop, and type hints. As a whole Python 3 is finally gaining popularity and we heavily recommend it over the older Python 2. Nearly all libraries are available for Python 3 and now is a good time to upgrade your legacy code base.

PHP 7 is a major new version that fixes a number of issues and brings new features and speed (see an overview here). PHP 7 is around twice as fast as PHP 5.6, which will have a big impact on large codebases and CMS systems like WordPress and Drupal. We recommend PHP The Right Way, which was updated for version 7. And if you need even more speed and don’t mind switching to an alternative runtime, check out HHVM, which Facebook uses and develops to run their website.

JavaScript also saw updates in the form of the ES2015 standard (used to be known as ES6). It brings us exciting new features and additions to the language. Thanks to most browsers adopting quick release schedules, support for ES2015 is great, and there is Babel.js which will help you bring your code to older browsers.

Node.js saw a lot of changes this year, with the community splitting between Node.js and io.js, and then joining forces again. As a result we now have an actively maintained project with lots of contributors and two versions of Node – a solid LTS (long term support) release, which gives stability for long lived projects and large companies, and a non-lts version which is quick to add new JavaScript features.

Swift 2 was released earlier this year. This is Apple’s vision for a modern programming language that eases the development of apps on iOS and OS X. As of a few weeks ago, Swift is open source and has already been ported on Linux. This means that it is now possible to build backends and server side software with it.

Go 1.5 was released a few months ago, and brough major architectural changes. In 2015 it has grown in popularity and has been adopted in leading startups and open source projects. The language itself is relatively simple, so learning it will be a weekend well spent.

TypeScript is a staticly typed language which compiles to JavaScript. It is developed by Microsoft and has perfect integration with Visual Studio and the open source Visual Studio Code editors. It will soon be quite popular, as the upcoming Angular 2 is written in it. Static typing benefits large teams and large code bases the most, so if one of these applies to you, or you are just curious, you should give TypeScript a try.

For the adventurous, you can try out one the functional languages like Haskell or Clojure. There are also interesting high performance languages like Rust and Elixir. If you are looking for a programming job, career languages like Java (which has some nice features in its 8th version) and C# (which thanks to Visual Studio Code and .net core can be run and developed cross platform) would be a good investment of your time in 2016.

Learn one or more of these: Python 3, Go, PHP 7, ES2015, Node.js, Swift, TypeScript


javascript

JavaScript Frameworks

JavaScript is a very important piece of the web development stack, so we are giving it dedicated section in our overview. There were two new standards this year – Service Workers and Web Assembly, which shape how web apps are developed from now on. There were also a number of new framework releases which we think you should keep a close eye on in 2016:

Angular.js has become the go-to JavaScript framework for enterprises and large companies. It has been known for some time that the next major version of the framework was coming, and earlier this year Angular 2 was released as a development preview. It is a total rewrite of Angular 1 and according to us is a great improvement over it. It is almost guaranteed to become the enterprise framework of choice once it is released, and Angular 2 experience will be a great addition to your CV. Our advice is to wait a few months for the final version to ship before picking it up, but you can read through their quick start guide right now.

React continued its ascend throughout 2015 and has seen new releases throughout the year and new projects adopting it as their framework of choice. It shipped new development tools a few months ago. Facebook also released React Native which is a framework for building mobile apps for Android and iOS, which combines a native frontend with React running in a background JavaScript thread. See a quick tutorial about React that we published this year.

Polymer 1.0 was released in May. This marks the first stable and production ready version. Polymer is based around Web Components, which is a standard for packaging HTML, JS and CSS into isolated widgets that can be imported into your web apps. Web Components are only supported in Chrome and Opera at the moment, but Polymer makes them available everywhere.

Ember.js also saw a new release. Ember 2 brings modularity and removes deprecated features and optimizes the codebase. Ember follows semantic versioning and maintainers of the framework are careful to make updating as easy as possible. If you need a framework with stability and easy migration to new versions, you can give Ember a try.

Learn one of these: Angular 2, React, Ember.js, Polymer, Web Components, Service Workers


frontend

Frontend

Bootstrap has become even more popular in the last year and is turning into a web development standard. Version 4 will come out in the next few months, which brings flexbox support and integrates SASS. It promises a smooth transition from V3 (unlike what we saw with v2 to v3 a couple of years ago), so you can feel confident that what you learn about Bootstrap 3 will be applicable to version 4.

Foundation is another frontend framework that is an alternative to Bootstrap. Version 6 was released earlier this year, which focuses on modularity so that you can include only the pieces that you need for a faster load time.

MDL is an official framework by Google for building material design web apps. It was released earlier this year and has a similar goal to Google’s other framework – Polymer, but is much easier to get started with. We have a wonderful overview which compares MDL with Bootstrap.

CSS preprocessors continue improving. Less and SASS are the two most popular at the moment, with mostly comparable feature sets. However, the news that Bootstrap 4 is migrating over to SASS gives it a slight edge over Less as the preprocessor to learn in 2016. Also, there is the newer PostCSS tool that is gaining mind share, but we recommend it only for devs which already have experience with preprocessors.

Learn one or more of these: Bootstrap, MDL, Foundation, SASS, LESS, PostCSS


backend

Backend

There has been a clear trend in web development over the last few years. More and more of our apps’ logic is shifted to the frontend, and the backend is only treated as an API. However there is still room for classic HTML-generating web apps, which is why we think that learning a classic full stack framework is still important.

Depending on which language you prefer, you have plenty of choice. For PHP you have Symfony, Zend, Laravel (and Lumen, its new lightweight alternative for APIs), Slim and more. For Python – Django and Flask. For Ruby – Rails and Sinatra. For Java – Play and Spark. For Node.js you have Express, Hapi and Sails.js, and for Go you have Revel.

AWS Lambda was released last year, but the concept is now established and ready for production. This is a service which eliminates backend servers entirely and is infinitely scaleable. You can define functions which are called on specific conditions or when routes of your API are visited. This means that you can have an entirely serverless backend which you don’t have to think about.

Another trend are static site generators like Jekyll and Octopress (see a complete list here). These tools take a number of source files like text and images, and create an entire website with prerendered HTML pages. Developers, who would normally set up a WordPress blog with a database and an admin area, now prefer to generate their HTML pages ahead of time and only upload a static version of their site. This has the benefits of increased security (no backend to hack and database to manage) and fantastic performance. Combined with CDNs like MaxCDN and CloudFlare clients can request a page of the website and receive it from a server nearby, greatly reducing latency.

Learn one of these: A full stack backend framework, AWS Lambda, A static site generator


cms

CMS

We’ve included two of the most popular CMS systems here. Both are written in PHP and are easy to deploy and get started with. They enjoy big speedups from the new PHP 7 release.

In recent years WordPress has become much more than a simple blogging platform. It is a fully fledged CMS/Framework with plugins that make it possible to run any kind of website. High quality WordPress themes are a big market, and lots of freelancers make their living by developing for WordPress. With projects like WP-API you can use WordPress as a REST API backend.

Drupal 8 was released this year. It is a full rewrite that focuses on modern development practices. It makes use of Symfony 2 components and Composer packages and the Twig templating engine. Millions of websites run Drupal, and it is a good choice for content heavy portals.


databases

Databases

This year the web development community lost some of its enthusiasm for NoSQL databases, and instead returned to relational databases like Postgres and MySQL. Notable exceptions to this trend are RethinkDB and Redis which gained mind share, and we recommend that you try them out in 2016.

Postgres is a popular relational database engine which sees a lot of development activity and is constantly improved with new features. Version 9.5 is expected soon. It will bring better support for JSONB columns for holding schema-less data (replacing any need for a separate NoSQL database) and the long awaited upsert operation, which simplifies INSERT-or-UPDATE queries. You might want to look into it, once it is released in 2016.

MySQL is the the most popular open source database system and is installed on most hosting providers out there. With version 5.7, MySQL also offers JSON columns for storing schema-less data. If you are just starting out with backend development, you will most likely be looking at connecting to a MySQL database that your hosting provider has set up for you. It is probably going to be an older version, so you might not be able to try out the JSON type. MySQL is included in popular packages like XAMPP and MAMP so it is easy to get started with.

Learn one of these: Redis, RethinkDB, MySQL/MariaDB, PostgreSQL


mobile-apps

Mobile Apps

Mobile platforms are always evolving and smartphone hardware now rivals low end laptops in performance. This is great news for hybrid mobile frameworks, as mobile apps built using web technologies can now offer a smooth, native-like experience.

We have a nice overview of hybrid mobile frameworks that you might want to check out. You have the popular Ionic framework and Meteor which recently had its 1.0 version and is also suitable for mobile app development. Facebook launched React Native, which runs React components in a background JavaScript thread and updates a native UI, allowing you to have mostly identical code for both iOS and Android.

Learn one of these: Ionic, React Native, Meteor


editors-and-tools

Editors and Tools

The Atom editor reached version 1.0 this year. It is a free and powerful code editor that is built using web technologies. It has lots of packages available for it and a large community. It offers smart autocompletion and integrates with plugins for code refactoring and linting. Not to mention that it has lots of beautiful themes to chose from, and you can customize it by writing CoffeeScript and CSS. Facebook has used this extensibility and launched the Nuclide editor.

Microsoft surprised everybody when they released their Visual Studio Code editor earlier this year. It is a lightweight IDE that supports a number of languages and runs on Windows, Linux and OS X. It offers the powerful IntelliSense code inspection feature and integrates a debugger for ASP.Net and Node.js.

NPM, the package manager of Node.js, has exploded in popularity and has become the packaging standard for frontend and node developers. This is the easiest way to manage the JavaScript dependencies for your project and getting started with it is easy.

Even for a solo developer Git is a necessity these days. Its serverless model allows you to turn any folder into a version controlled repository, which you can then push to Bitbucket or Github, and sync across computers. If you haven’t used Git yet, we recommend that you add it to your list of things to learn in 2016.

Learn one of these: Atom, Visual Studio Code, NPM, Git


making-things

Making Things

The Raspberry PI foundation delivered an early Christmas present this year, with the release of the Raspberry PI Zero – a $5 computer that is fast and power efficient. It runs Linux, so you can turn it into a server, a home automation device, a smart mirror, or to embed it into a dumb appliance and create that internet enabled coffee brewer you’ve been dreaming of. 2016 is the year to get a Raspberry.


Onto An Awesome 2016!

We’ve had a great 2015 and by the looks of it 2016 is going to be even more awesome. What’s on your list of things to learn in 2016?

Source:: Tutorialzine.com

The 10 Most Entertaining Stackoverflow Questions Of All Time

By Danny Markov

most-entertaining-stack-overflow-questions

Oh Stack Overflow, what would we do without you! You save us countless hours of bug fixing with a single spot on answer. But there was a time when Stack Overflow wasn’t only for technical answers, and a few entertaining gems could slip through. We’ve collected a few of our most favorite ones for your enjoyment.

Our Top 10

Here are our favorite entertaining Stack Overflow questions. They aren’t sorted by up votes or anything, we are going to let you decide which ones you like best. If we’ve missed your favorite, add it to our comment section!


Although this question is from 2011 and no one uses the HTML bgcolor attribute anymore, it’s still funny that someone tried to color their div chucknorris. Also, in case you were wondering, here is a chart showing which color represents the names of popular celebrities.


10. What's your favorite programmer cartoon?

A huge compilation of funny images and comics. Be careful, you might waste an entire work day with this one. Credit goes to xkcd for providing us with nerdy entertainment.


5. What is the best comment in source code you have ever encountered?

Some people don’t comment their code at all causing confusion and bewilderment, others add meaningful and on point hints to aid their colleagues and their future selves. And then there are the people in this thread.


13. What is your best programmer joke?

Some of these are bad, some of these are good, some of these are so bad they are good. You know a good joke that is not in the list? Post it to our comment section!


3. Pair socks from a pile efficiently?

Ever feel like your amazing programming skills are useless outside of the computer world? This questions proves they aren’t! Apply your knowledge and fix a very real everyday laundry problem.


11. What's the difference between JavaScript and Java?

This question is another evidence that Stack Overflow has a sense of humor. Choose your favorite answer and the next time someone asks you this question seize the opportunity!


4. Is it possible to apply CSS to half of a character?

Have you ever needed to style only half of a character? Neither have we, but surprisingly it is possible! In an incredibly detailed answer, the stack overflow user Arbel shows different techniques for doing it. The code has been released as a jQuery plugin.


9. Check checkbox checked property

How many checkboxes could a checkbox check if a checkbox could check checkboxes? But no, seriously, this is a helpful question solving a very common problem.


1. Why does ++[[]][+[]]+[+[]] return the string 10?

JavaScript is a weird language that often times works in mysterious and unpredictable ways. The snipped in question is not Brainfuck but valid JavaScript. Thankfully Stack Overflow is full with people who now their JS, and they took the time to explain how this mind bending code works.


12. What was the strangest coding standard rule that you were forced to follow?

Have you ever thought about how much you hate your workplace? Well, at lest it doesn’t impose nonsensical coding standard rules like the ones in this thread.

Bonus

7. Why does this code using random strings print hello world?

This question was asked in the java section, but the topic applies to all programming languages – random isn’t really random, it’s pseudorandom. Feel free to use this information to confuse other coders.

Source:: Tutorialzine.com