About the Author:

Insert, Remove, Splice and Replace elements with Array.splice()

August 4th, 2018

When you already have an existing array and need to make some edits, the Array.splice() method comes in handy. The splice() method allows you to INSERT, REMOVE, and REPLACE elements from a javascript array.

Before jumping into any examples, let’s start by taking a look at the arguments passed into the splice() method.
Array.splice(start_index, number_of_elements_to_remove);

  • start_index refers to the position in the array where the Insertion or Removal of elements will begin.
  • number_of_elements_to_remove will begin at the start index, and remove an element from array
  • all arguments following number_of_elements_to_remove will get inserted in to the array from the start_index. these arguments inserted into the array can be of any data type including strings, numbers, booleans, objects, functions, null, undefined, etc…

For a more in depth look at the Array.prototype.splice() javascript method parameters check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Let’s start with a simple example demonstrating how to INSERT a number into an array with the Array.splice() method.
Imagine we have the following array [1,3,4] and we want to insert a 2 between the 1 and 3 in this javascript array.
The following code example will INSERT the number 2 between the 1 and 3.


        var my_array = [1,3,4];
        var start_index = 1;
        var number_of_elements_to_remove = 0;
        my_array.splice(start_index, number_of_elements_to_remove, 2);
        console.log(my_array);
        //[1,2,3,4];
    

Take note when using the array.splice() method, the splice() method acts directly on the array. So instead of returning a new array, calling the splice() method on my_array, will update my_array.

Next, let’s take a look at an example of REMOVING an element from an array in javascript.


        var my_array = ["a","b","c","k","d"];
        var start_index = 3
        var number_of_elements_to_remove = 1;
        var removed_elements = my_array.splice(start_index, number_of_elements_to_remove);
        console.log(removed_elements);
        //["k"]
        console.log(my_array);
        //["a","b","c","d"];
    

Take note when using the array.splice() method to remove elements, an array of the removed elements will get returned

Lastly, let’s take a look at REPLACING some elements in a javascript array with the splice() method


        var my_array = ["baseball", "basketball", "tennis", "golf"];
        var start_index = 1
        var number_of_elements_to_remove = 2;
        var removed_elements = my_array.splice(start_index, number_of_elements_to_remove, "boxing", "bowling", "volleyball");
        console.log(removed_elements);
        //["tennis", "golf"]
        console.log(my_array);
        //["baseball", "boxing", "bowling", "volleyball", "golf"];
    

The above example replaces the sports “basketball” and “tennis” with “boxing”, “bowling”, and “volleyball”. The above example may seem a little confusing because of all of the operations that took place. So, let’s break down the operations step by step. First, we tell the splice method to start at my_array[1]. Then, number_of_elements_to_remove is set to 2, so remove my_array[1] and my_array[2]. Lastly, from the start_index my_array[1] insert each of the arguments into my_array one by one.

For more examples of using the splice() method, check out https://www.tutorialspoint.com/javascript/array_splice.htm or https://www.hacksparrow.com/javascript-array-splice-syntax-and-examples.html

The splice() method works well when looking to INSERT or REMOVE values from a javascript array. If your array is already sorted, the splice() method works well to explicitly position new values exactly where you want in the array. The splice() method also works well when looking to remove values from an array by index. Something to pay close attention to is that the splice() method acts directly on the array. Only the values that were removed, deleted, or stripped from the array will get returned.

About the Author:

Using Horizon/RethinkDB with React

August 9th, 2017

Horizon is an open source Backend as a Service (BaaS) that allows developers to easily build data-driven web and mobile applications. Horizon, which is built on RethinkDB and by the RethinkDB team, facilitates common application development tasks like backend setup, real-time data transfer, security and scalability. Horizon can be run locally, on a private server or in the cloud.

This tutorial will give you an introduction to Horizon and RethinkDB while also showing you how to build a simple app with Horizon and React. This will give you a simple and scalable architecture for building your own much more complex apps.

A Quick Note About the State of Horizon/RethinkDB

On October 5th 2016, the company behind RethinkDB announced it would be shut down. This left many users believing the entire project was being cancelled and shuttered. In actuality, RethinkDb and Horizon became fully open source and community driven. On February 6th 2017, the Cloud Native Computing Foundation (CNCF) purchased the rights to the RethinkDB source code and contributed it to the Linux Foundation. This gave the project the necessary support to keep the project alive and facilitate its continuous development.

Horizon + React = Awesome Combo

Horizon and React is a pair made in heaven for developers. Horizon takes charge of all the backend complexities and React facilitates building a modular, reactive frontend. Horizon handles the distribution of data in real-time while React keeps the clients updated. Everything scales and everything has high performance and low latency.

When there is a change in the app’s state, ReactJS will efficiently redraw the necessary components by diffing between the virtual DOM and the existing DOM (and making only the required changes). Horizon notifies all subscribed clients when there is a data update, so they can either download the data again or simply apply the change into its local copy when the original data is too large to fully reload on each change. Together, Horizon and React allow for a simple way to build real-time data-driven applications.

Building a ‘ToBring’ App

To demonstrate how they work together, we’ll build a ‘ToBring’ app (not another another ToDo!). This application will track a list of items we need for a party. This app will allow users to add items in a section that we will call “We need list” or move them to another list called “We have list” and add the name of the user who will bring the item.

To see all the code for this demo, check out this repo.

To keep the setup simple, we’ll use create-react-app. To start the React part of the application, first install create-react-app with the command

npm install -g create-react-app

Then you’ll need to initialize a new app with the commands

create-react-app party_checklist

and

an npm install/start

Once ready, it should launch on your browser with the address http://localhost:3000/ and will auto-reload every time you change the source code.

React is all about components. The main component of our app will have three sub-components: one to add a new item, one to hold the “we need list” and another to hold the “we have list”. Here’s a quick visual of how these components will fit together.

We will need to know the user’s name for keeping track of what they bring. Let’s put a simple input to get the name of the active user into the main component.

If you are wondering, Horizon does include options to authenticate, add permissions and even Transport Layer Security to our app, but that is beyond the scope of this tutorial.

Here’s how we’ll code up the name input:

app.js

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      // A holder for the user name
      user : '',
    };
    // A binding to call updateUser without the () suffix
    this.updateUser = this.updateUser.bind(this);
  }

  render() {
    return (
      <div
        className= 'app'>
        <h1>Party Checklist</h1>
        <p>I am:</p>
        <input
          value = {this.state.user}
          onChange = {this.updateUser} />
      </div>
    );
  }

  // A method to update the state in response to a synthetic event
  updateUser(e) {
    this.setState({user: e.target.value});
  }
}

It is important to remember how we use the constructor to hold the state and also to create bindings to expose methods, without it “this” will return “undefined” when the method is actually called. This is how React handles events, also notice how “updateUser” has a parameter called “e”, this is called a synthetic event.

Now let’s add the NewItem component:

app.js

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user : '',
    };
    this.updateUser = this.updateUser.bind(this);
  }

  render() {
    return (
      <div
        className= 'app'>
        <h1>Party Checklist</h1>
        <p>I am:</p>
        <input
          value = {this.state.user}
          onChange = {this.updateUser} />
        <NewItem />
      </div>
    );
  }

  updateUser(e) {
    this.setState({user: e.target.value});
  }
}

class NewItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      item  : '',
    };
    this.updateItem = this.updateItem.bind(this);
  }
  render() {
    return (
      <div>
        <p>Add to need list:</p>
        <form>
          <input
            value = {this.state.item}
            onChange = {this.updateItem} />
        </form>
      </div>
    );
  }

  updateItem(e) {
    this.setState({item: e.target.value});
  }
}

JSX allows you import the “NewItem” component into “App” similar to custom web components on HTML.

Now let’s make a component for the WeNeedList, notice how it was an “items” list in its properties, this means the value will be passed when it is declared inside another component. When dealing with lists in React, you can use a simple map method.

app.js

class WeNeedList extends React.Component {
  render() {
    return (
      <div>
        <h2>We need...</h2>
        {this.props.items.map(item => (
          <div
            className= 'row'>
            <button
              className= 'remove'>
              x
            </button>
            {item.description}
            <button
              className= 'add'>
              +
            </button>
          </div>
        ))}
      </div>
    );
  }
}

Now lets add “WeNeedList” to “App”.

app.js

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      weNeedList : [],
      user : '',
    };
    this.updateUser = this.updateUser.bind(this);
  }

  render() {
    return (
      <div
        className= 'app'>
        <h1>Party Checklist</h1>
        <p>I am:</p>
        <input
          value = {this.state.user}
          onChange = {this.updateUser} />
        <NewItem />
        <WeNeedList
          items = {this.state.weNeedList}
          user = {this.state.user} />
      </div>
    );
  }

  updateUser(e) {
    this.setState({user: e.target.value});
  }
}

See how “App”will hold the state of the list and will pass it to “WeNeedList” as parameters. Inside “WeNeedList” we can read this values from props.

And finally we need to make a WeHaveList component:

app.js

class WeHaveList extends React.Component {
  render() {
    return (
      <div>
        <h2>We have...</h2>
        {this.props.items.map(item => (
          <div
            className= 'row'
            key = {item.id}>
            <button
              className= 'cancel'>
              x
            </button>
            {item.description} from {item.user}
          </div>
        ))}
      </div>
    );
  }
}

And also add it to the “App” component:

app.js

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      weNeedList : [],
      weHaveList : [],
      user : '',
    };
    this.updateUser = this.updateUser.bind(this);
  }

  render() {
    return (
      <div
        className= 'app'>
        <h1>Party Checklist</h1>
        <p>I am:</p>
        <input
          value = {this.state.user}
          onChange = {this.updateUser} />
        <NewItem />
        <WeNeedList
          items = {this.state.weNeedList}
          user = {this.state.user} />
        <WeHaveList
          items = {this.state.weHaveList} />
      </div>
    );
  }

  updateUser(e) {
    this.setState({user: e.target.value});
  }
}

Now the core of our app is complete! But it doesn’t do anything yet, for that, we need to add Horizon and create a few methods inside our components.

To install Horizon in your machine, simply run the command npm install -g horizon.

Horizon, like create-react-app, automatically initializes everything. You only need to provide the name of the app you want to create with the command hz init party_checklist; it is important that you run this from the same place from where you created the app, so it will just add new files to the project instead of creating a new one. You must always start with React and then add Horizon.

Horizon needs RethinkDB to work. Before launching your Horizon server, make sure you have RethinkDB running on your machine. Refer to the official documentation for detailed instructions on how to run it on your system. The simplest way for Mac users is to use Homebrew to install it.

Now let’s configure Horizon to look for RethinkDB in your local machine. To do so, go to .hz => config.toml and replace it with the following:

bind = [ "localhost" ]
port = 8181

connect = "localhost:28015"
start_rethinkdb = false

To launch your Horizon server locally, go the folder with your project and run hz serve –dev, this will start your local Horizon server on port 8181. Note that you always need to keep one instance running React and another running Horizon while you are developing.

Before hitting the code, let’s learn a few basic Horizon concepts:

Horizon groups data into horizon collections and each collection is backed by a RethinkDB table. All documents inside a collection are identified by a unique key stored in the id field.

Horizon provides a very simple yet powerful API that helps you handle the following aspects:

In this tutorial, we will be focusing on the first two, DB connection and data collections.

ReactJS is designed to use an unidirectional data flow, so the data always flow from the DB into the parts of the UI that represents it. You can stream data right into its specific component or stream many into the parent and then your pass it down via component props.

Here’s a visual to help you make sense of the data flow in this app:

Note that any change in the data is sent from one React client into Horizon and Horizon sends it back to all React apps so they can update their view, this flow makes sure that all clients are always watching the same without inconsistencies. Also note that the data always flows in one direction between Horizon and React.

Let’s add the Horizon client library into our app. First run npm install @horizon/client to get the horizon client installed locally and make an instance of the client holding a connection to our local server in app.js.

app.js

import Horizon from '@horizon/client';
const horizon = new Horizon({host: 'localhost:8181'});

Now let’s configure React to open a connection with the Horizon server right after everything has loaded correctly using the componentDidMount() lifecycle method. We will include some watchers to log when the connection to Horizon is ready and when it gets disconnected.

app.js

class App extends Component {

  // ...

  componentDidMount(){
    horizon.connect();

    horizon
      .onReady()
        .subscribe(() =>
          console.info('Connected to Horizon server'));

    horizon
      .onDisconnected()
        .subscribe(() =>
          console.info('Disconnected from Horizon server'));
  }
}

Remember how we talked about collections in Horizon? Our app will use two Horizon collections, one for the “we need list” and other for the “we have list”. Let’s store a reference to them at the top of app.js.

app.js

import Horizon from '@horizon/client';

const horizon = new Horizon({host: 'localhost:8181'});
const weNeedList_collection = horizon('weNeedList');
const weHaveList_collection = horizon('weHaveList');

Horizon makes it very easy to watch and apply for changes in real time, you can even add custom logic and subscribe to a feed of changes. A common practice is to use the timestamp of each object as its ID and request the collection sorted by the ID, so they will always come in chronological order. Let’s do that for both collections.

app.js

class App extends Component {

  // ...

  componentDidMount(){
    horizon.connect();

    // ...

    weNeedList_collection
      .order('id')
        .watch()
          .subscribe(allItems =>
            this.setState({weNeedList: allItems}),
            error => console.error(error));

    weHaveList_collection
      .order('id')
        .watch()
          .subscribe(allItems =>
            this.setState({weHaveList: allItems}),
            error => console.error(error));
  }

Now it’s time to add data manipulation methods, for this app we will use insert and remove; in both cases we only need to pass the item we wish to insert or remove as the parameter.

Let’s start by updating NewItem

app.js

class NewItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      item  : '',
    };
    this.updateItem = this.updateItem.bind(this);
    this.insertItem = this.insertItem.bind(this);
  }
  render() {
    return (
      <div>
        <p>Add to need list:</p>
        <form
          onSubmit = {this.insertItem}>
          <input
            value = {this.state.item}
            onChange = {this.updateItem} />
        </form>
      </div>
    );
  }

  updateItem(e) {
    this.setState({item: e.target.value});
  }

  insertItem(e) {
    e.preventDefault();
    const newItem = {
      description: this.state.item,
      id: Date.now()
    };

    weNeedList_collection.insert(newItem);
    this.setState({item: ''});
  }
}

Now let’s do the same for WeNeedList.

app.js

class WeNeedList extends React.Component {
  render() {
    return (
      <div>
        <h2>We need...</h2>
        {this.props.items.map(item => (
          <div
            className= 'row'>
            <button
              className= 'remove'
              onClick= {() => this.remove(item)}>
              x
            </button>
            {item.description}
            <button
              className= 'add'
              onClick= {() => this.moveToHave(item)}>
              +
            </button>
          </div>
        ))}
      </div>
    );
  }

  remove(item) {
    weNeedList_collection.remove(item);
  }

  moveToHave(item) {
    weNeedList_collection.remove(item);
    item.user = this.props.user;
    weHaveList_collection.insert(item);
  }
}

And finally for WeHaveList.

app.js

class WeHaveList extends React.Component {
  render() {
    return (
      <div>
        <h2>We have...</h2>
        {this.props.items.map(item => (
          <div
            className= 'row'
            key = {item.id}>
            <button
              className= 'cancel'
              onClick= {() => this.returnToNeed(item)}>
              x
            </button>
            {item.description} from {item.user}
          </div>
        ))}
      </div>
    );
  }

  returnToNeed(item) {
    weHaveList_collection.remove(item);
    weNeedList_collection.insert(item);
  }
}

And we are finished! Now you know all the basics to start building amazing real time apps using ReactJS and Horizon.

The Horizon-React combo greatly simplifies development, allowing you and your team to develop applications and prototypes in a very short time while also making it easy to scale, maintain and debug those apps in the future, this greatly reduces costs and makes you and your team more competitive in the global market.

About the Author:

45 Useful JavaScript Tips, Tricks and Best Practices

April 12th, 2017

As you know, JavaScript is the number one programming language in the world, the language of the web, of mobile hybrid apps (like PhoneGap or Appcelerator), of the server side (like NodeJS or Wakanda) and has many other implementations. It’s also the starting point for many new developers to the world of programming, as it can be used to display a simple alert in the web browser but also to control a robot (using nodebot, or nodruino). The developers who master JavaScript and write organized and performant code have become the most sought after in the job market.

In this article, I’ll share a set of JavaScript tips, tricks and best practices that should be known by all JavaScript developers regardless of their browser/engine or the SSJS (Server Side JavaScript) interpreter.

Note that the code snippets in this article have been tested in the latest Google Chrome version 30, which uses the V8 JavaScript Engine (V8 3.20.17.15).

1 – Don’t forget var keyword when assigning a variable’s value for the first time.

Assignment to an undeclared variable automatically results in a global variable being created. Avoid global variables.

2 – use === instead of ==

The == (or !=) operator performs an automatic type conversion if needed. The === (or !==) operator will not perform any conversion. It compares the value and the type, which could be considered faster than ==.

[10] === 10    // is false
[10]  == 10    // is true
'10' == 10     // is true
'10' === 10    // is false
 []   == 0     // is true
 [] ===  0     // is false
 '' == false   // is true but true == "a" is false
 '' ===   false // is false 

3 – undefinednull, 0, falseNaN'' (empty string) are all falsy.
4 – Use Semicolons for line termination

The use of semi-colons for line termination is a good practice. You won’t be warned if you forget it, because in most cases it will be inserted by the JavaScript parser. For more details about why you should use semi-colons, take a look to this artice: http://davidwalsh.name/javascript-semicolons.

5 – Create an object constructor

function Person(firstName, lastName){
    this.firstName =  firstName;
    this.lastName = lastName;        
}  

var Saad = new Person("Saad", "Mousliki");

6 – Be careful when using typeofinstanceof and constructor.

  • typeof : a JavaScript unary operator used to  return a string that represents the primitive type of a variable,  don’t forget that typeof null will return “object”, and for the majority of object types (Array, Date, and others) will return also “object”.
  • constructor : is a property of the internal prototype property, which could be overridden by code.
  • instanceof : is another JavaScript operator that check in all the prototypes chain the constructor it returns true if it’s found and false if not.
var arr = ["a", "b", "c"];
typeof arr;   // return "object" 
arr  instanceof Array // true
arr.constructor();  //[]

7 – Create a Self-calling Function

This is often called a Self-Invoked Anonymous Function or Immediately Invoked Function Expression (IIFE). It is a function that executes automatically when you create it, and has the following form:

(function(){
    // some private code that will be executed automatically
})();  
(function(a,b){
    var result = a+b;
    return result;
})(10,20)

8 – Get a random item from an array

var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];

var  randomItem = items[Math.floor(Math.random() * items.length)];

9 – Get a random number in a specific range

This code snippet can be useful when trying to generate fake data for testing purposes, such as a salary between min and max.

var x = Math.floor(Math.random() * (max - min + 1)) + min;

10 – Generate an array of numbers with numbers from 0 to max

var numbersArray = [] , max = 100;

for( var i=1; numbersArray.push(i++) < max;);  // numbers = [1,2,3 ... 100] 

11 – Generate a random set of alphanumeric characters

function generateRandomAlphaNum(len) {
    var rdmString = "";
    for( ; rdmString.length < len; rdmString  += Math.random().toString(36).substr(2));
    return  rdmString.substr(0, len);

}

12 – Shuffle an array of numbers

var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
numbers = numbers.sort(function(){ return Math.random() - 0.5});
/* the array numbers will be equal for example to [120, 5, 228, -215, 400, 458, -85411, 122205]  */

A better option could be to implement a random sort order by code (e.g. : Fisher-Yates shuffle), than using the native sort JavaScript function. For more details take a look to this discussion.

13 – A string trim function

The classic trim function of Java, C#, PHP and many other language that remove whitespace from a string doesn’t exist in JavaScript, so we could add it to the String object.

String.prototype.trim = function(){return this.replace(/^s+|s+$/g, "");};  

A native implementation of the trim() function is available in the recent JavaScript engines.

14 – Append an array to another array

var array1 = [12 , "foo" , {name "Joe"} , -2458];

var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
/* array1 will be equal to  [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */

15 – Transform the arguments object into an array

var argArray = Array.prototype.slice.call(arguments);

16 – Verify that a given argument is a number

function isNumber(n){
    return !isNaN(parseFloat(n)) && isFinite(n);
}

17 – Verify that a given argument is an array

function isArray(obj){
    return Object.prototype.toString.call(obj) === '[object Array]' ;
}

Note that if the toString() method is overridden, you will not get the expected result using this trick.

Or use…

Array.isArray(obj); // its a new Array method

You could also use instanceof if you are not working with multiple frames. However, if you have many contexts, you will get a wrong result.

var myFrame = document.createElement('iframe');
document.body.appendChild(myFrame);

var myArray = window.frames[window.frames.length-1].Array;
var arr = new myArray(a,b,10); // [a,b,10]  

// instanceof will not work correctly, myArray loses his constructor 
// constructor is not shared between frames
arr instanceof Array; // false

18 – Get the max or the min in an array of numbers

var  numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411]; 
var maxInNumbers = Math.max.apply(Math, numbers); 
var minInNumbers = Math.min.apply(Math, numbers);

19 – Empty an array

var myArray = [12 , 222 , 1000 ];  
myArray.length = 0; // myArray will be equal to [].

20 – Don’t use delete to remove an item from array

Use splice instead of using delete to delete an item from an array. Using delete replaces the item with undefined instead of the removing it from the array.

Instead of…

var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ]; 
items.length; // return 11 
delete items[3]; // return true 
items.length; // return 11 
/* items will be equal to [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154,       119]   */

Use…

var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ]; 
items.length; // return 11 
items.splice(3,1) ; 
items.length; // return 10 
/* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154,       119]   */

The delete method should be used to delete an object property.

21 – Truncate an array using length

Like the previous example of emptying an array, we truncate it using the length property.

var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];  
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].

As a bonus, if you set the array length to a higher value, the length will be changed and new items will be added with undefined as a value. The array length is not a read only property.

myArray.length = 10; // the new array length is 10 
myArray[myArray.length - 1] ; // undefined

22 – Use logical AND/ OR for conditions

var foo = 10;  
foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething(); 
foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();

The logical OR could also be used to set a default value for function argument.

function doSomething(arg1){ 
    arg1 = arg1 || 10; // arg1 will have 10 as a default value if it’s not already set
}

23 – Use the map() function method to loop through an array’s items

var squares = [1,2,3,4].map(function (val) {  
    return val * val;  
}); 
// squares will be equal to [1, 4, 9, 16] 

24 – Rounding number to N decimal place

var num =2.443242342;
num = num.toFixed(4);  // num will be equal to 2.4432

NOTE : the toFixed() function returns a string and not a number.

25 – Floating point problems

0.1 + 0.2 === 0.3 // is false 
9007199254740992 + 1 // is equal to 9007199254740992  
9007199254740992 + 2 // is equal to 9007199254740994

Why does this happen? 0.1 +0.2 is equal to 0.30000000000000004. What you need to know is that all JavaScript numbers are floating points represented internally in 64 bit binary according to the IEEE 754 standard. For more explanation, take a look to this blog post.

You can use toFixed() and toPrecision() to resolve this problem.

26 – Check the properties of an object when using a for-in loop

This code snippet could be useful in order to avoid iterating through the properties from the object’s prototype.

for (var name in object) {  
    if (object.hasOwnProperty(name)) { 
        // do something with name                    
    }  
}

27 – Comma operator

var a = 0; 
var b = ( a++, 99 ); 
console.log(a);  // a will be equal to 1 
console.log(b);  // b is equal to 99

28 – Cache variables that need calculation or querying

In the case of a jQuery selector, we could cache the DOM element.

var navright = document.querySelector('#right'); 
var navleft = document.querySelector('#left'); 
var navup = document.querySelector('#up'); 
var navdown = document.querySelector('#down');

29 – Verify the argument before passing it to isFinite()

isFinite(0/0) ; // false 
isFinite("foo"); // false 
isFinite("10"); // true 
isFinite(10);   // true 
isFinite(undefined);  // false 
isFinite();   // false 
isFinite(null);  // true  !!! 

30 – Avoid negative indexes in arrays

var numbersArray = [1,2,3,4,5]; 
var from = numbersArray.indexOf("foo") ;  // from is equal to -1 
numbersArray.splice(from,2);    // will return [5]

Make sure that the arguments passed to splice are not negative.

31 – Serialization and deserialization (working with JSON)

var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} }; 
var stringFromPerson = JSON.stringify(person); 
/* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}"   */ 
var personFromString = JSON.parse(stringFromPerson);  
/* personFromString is equal to person object  */

32 – Avoid the use of eval() or the Function constructor

Use of eval or the Function constructor are expensive operations as each time they are called script engine must convert source code to executable code.

var func1 = new Function(functionCode);
var func2 = eval(functionCode);

33 – Avoid using with() (The good part)

Using with() inserts a variable at the global scope. Thus, if another variable has the same name it could cause confusion and overwrite the value.

34 – Avoid using for-in loop for arrays

Instead of using…

var sum = 0;  
for (var i in arrayNumbers) {  
    sum += arrayNumbers[i];  
}

…it’s better to use…

var sum = 0;  
for (var i = 0, len = arrayNumbers.length; i < len; i++) {  
    sum += arrayNumbers[i];  
}

As a bonus, the instantiation of i and len is executed once because it’s in the first statement of the for loop. Thsi is faster than using…

for (var i = 0; i < arrayNumbers.length; i++)

Why? The length of the array arrayNumbers is recalculated every time the loop iterates.

NOTE : the issue of recalculating the length in each iteration was fixed in the latest JavaScript engines.

35 – Pass functions, not strings, to setTimeout() and setInterval()

If you pass a string into setTimeout() or setInterval(), the string will be evaluated the same way as with eval, which is slow. Instead of using…

setInterval('doSomethingPeriodically()', 1000);  
setTimeout('doSomethingAfterFiveSeconds()', 5000);

…use…

setInterval(doSomethingPeriodically, 1000);  
setTimeout(doSomethingAfterFiveSeconds, 5000);

36 – Use a switch/case statement instead of a series of if/else

Using switch/case is faster when there are more than 2 cases, and it is more elegant (better organized code). Avoid using it when you have more than 10 cases.

37 – Use switch/case statement with numeric ranges

Using a switch/case statement with numeric ranges is possible with this trick.

function getCategory(age) {  
    var category = "";  
    switch (true) {  
        case isNaN(age):  
            category = "not an age";  
            break;  
        case (age >= 50):  
            category = "Old";  
            break;  
        case (age <= 20):  
            category = "Baby";  
            break;  
        default:  
            category = "Young";  
            break;  
    };  
    return category;  
}  
getCategory(5);  // will return "Baby"

38 – Create an object whose prototype is a given object

It’s possible to write a function that creates an object whose prototype is the given argument like this…

function clone(object) {  
    function OneShotConstructor(){}; 
    OneShotConstructor.prototype= object;  
    return new OneShotConstructor(); 
} 
clone(Array).prototype ;  // []

39 – An HTML escaper function

function escapeHTML(text) {  
    var replacements= {"<": "&lt;", ">": "&gt;","&": "&amp;", """: "&quot;"};                      
    return text.replace(/[<>&"]/g, function(character) {  
        return replacements[character];  
    }); 
}

40 – Avoid using try-catch-finally inside a loop

The try-catch-finally construct creates a new variable in the current scope at runtime each time the catch clause is executed where the caught exception object is assigned to a variable.

Instead of using…

var object = ['foo', 'bar'], i;  
for (i = 0, len = object.length; i <len; i++) {  
    try {  
        // do something that throws an exception 
    }  
    catch (e) {   
        // handle exception  
    } 
}

…use…

var object = ['foo', 'bar'], i;  
try { 
    for (i = 0, len = object.length; i <len; i++) {  
        // do something that throws an exception 
    } 
} 
catch (e) {   
    // handle exception  
} 

41 – Set timeouts to XMLHttpRequests

You could abort the connection if an XHR takes a long time (for example, due to a network issue), by using setTimeout() with the XHR call.

var xhr = new XMLHttpRequest (); 
xhr.onreadystatechange = function () {  
    if (this.readyState == 4) {  
        clearTimeout(timeout);  
        // do something with response data 
    }  
}  
var timeout = setTimeout( function () {  
    xhr.abort(); // call error callback  
}, 60*1000 /* timeout after a minute */ ); 
xhr.open('GET', url, true);  

xhr.send();

As a bonus, you should generally avoid synchronous XHR calls completely.

42 – Deal with WebSocket timeout

Generally when a WebSocket connection is established, a server could time out your connection after 30 seconds of inactivity. The firewall could also time out the connection after a period of inactivity.

To deal with the timeout issue you could send an empty message to the server periodically. To do this, add these two functions to your code: one to keep alive the connection and the other one to cancel the keep alive. Using this trick, you’ll control the timeout.

Add a timerID

var timerID = 0; 
function keepAlive() { 
    var timeout = 15000;  
    if (webSocket.readyState == webSocket.OPEN) {  
        webSocket.send('');  
    }  
    timerId = setTimeout(keepAlive, timeout);  
}  
function cancelKeepAlive() {  
    if (timerId) {  
        cancelTimeout(timerId);  
    }  
}

The keepAlive() function should be added at the end of the onOpen() method of the webSocket connection and the cancelKeepAlive() at the end of the onClose() method.

43 – Keep in mind that primitive operations can be faster than function calls. Use VanillaJS.

For example, instead of using…

var min = Math.min(a,b); 
A.push(v);

…use…

var min = a < b ? a : b; 
A[A.length] = v;

44 – Don’t forget to use a code beautifier when coding. Use JSLint and minification (JSMin, for example) before going live.

45 – JavaScript is awesome: Best Resources To Learn JavaScript

About the Author:

Use JavaScript to Export Your Data as CSV

April 7th, 2017

Do you know what annoys me? When I have my data in a web application and I can’t get it out. And if you’re not giving your users a way to export their data, then they’re annoyed too.

Today I’m going to show you how simple it is to provide CSV downloads in your application.

All that’s needed is a little Javascript and HTML. You don’t need a fancy $2,000 control suite or any server-side code.

First, we need some data. For this example we will turn an array of objects into a CSV download for the user:

var stockData = [
{
Symbol: "AAPL",
Company: "Apple Inc.",
Price: 132.54
},
{
Symbol: "INTC",
Company: "Intel Corporation",
Price: 33.45
},
{
Symbol: "GOOG",
Company: "Google Inc",
Price: 554.52
},
];

Now we need a function that will take any array of objects and create CSV data:

function convertArrayOfObjectsToCSV(args) {
var result, ctr, keys, columnDelimiter, lineDelimiter, data;

data = args.data || null;
if (data == null || !data.length) {
return null;
}

columnDelimiter = args.columnDelimiter || ',';
lineDelimiter = args.lineDelimiter || '\n';

keys = Object.keys(data[0]);

result = '';
result += keys.join(columnDelimiter);
result += lineDelimiter;

data.forEach(function(item) {
ctr = 0;
keys.forEach(function(key) {
if (ctr > 0) result += columnDelimiter;

result += item[key];
ctr++;
});
result += lineDelimiter;
});

return result;
}

First the function loops through the keys on one of the objects to create a header row, followed by a newline. Then we loop through each object and write out the values of each property.

Here’s what you end up with:

Symbol,Company,Price
AAPL,Apple Inc.,132.54
INTC,Intel Corporation,33.45
GOOG,Google Inc,554.52

Now we need a function that will take this data and turn it into a CSV file for download:

function downloadCSV(args) {
var data, filename, link;
var csv = convertArrayOfObjectsToCSV({
data: stockData
});
if (csv == null) return;

filename = args.filename || 'export.csv';

if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv);

link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
link.click();
}

This function takes the CSV we created and prepends a special string that tells the browser that our content is CSV and it needs to be downloaded:

data:text/csv;charset=utf-8,

So now we have:

data:text/csv;charset=utf-8,Symbol,Company,Price
AAPL,Apple Inc.,132.54
INTC,Intel Corporation,33.45
GOOG,Google Inc,554.52

We set the href attribute on our link to the above string. We also set the download attribute on our link to the filename we want to see for our download stock-data.csv

Then in our html we have a simple link that we can use to kick off things and test it out:

Download CSV

And when you click this link here’s what should happen:

You should get a download in the browser called stock-data.csv and then when you open it, we see the data in the expected table format.

The meat of this example happens in less than 50 lines of code. The code loops through your objects generically, so it doesn’t matter what properties are on your objects. If each object had 100 or 3 properties it would work just as well.

It’s also a nifty trick that you can create a download so easily in the browser. Not all developers know that you can do that. In fact, that same special string can be modified to allow other types of downloads.

Here’s the full example if you want to play with it:

<!doctype html>  
  


Download CSV%MINIFYHTML7ad26fcd59560c66b6f113ecdd1390df15%

About the Author:

ES6 One Liners to Show Off

March 30th, 2017

This is a guest post by Hemanth H.M and was originally published on H3manth.com.

Here is a collection of ES6 one liners to show off!

(more…)

About the Author:

ES6: What Are the Benefits of the New Features in Practice?

March 30th, 2017

This is a guest post by Jani Hartikainen and was originally published on CodeUtopia.

You’ve probably seen people talk about the features in JavaScript’s 6th edition, ES6, or ECMAScript 6. Promises, let keyword, iterators, etc. But why should you care? I certainly heard a lot about it, but I hadn’t looked into it because I wasn’t interested in theory, but rather the benefits I would get in my day to day work. Is it just feature-bloat for sake of having fancy things in the language, or are they actually useful? I then did some research and discovered a number of very useful features in ES6 that you can start taking advantage of right now. Let’s take a look at the most useful ones

Can you actually use ES6?

Before we go ahead, let’s address a critical issue: Can you use these features without worrying that it’ll break in older browsers? Edge, Chrome, Firefox and Safari all have most of ES6 features implemented. With older browsers, you will either need a shim for some parts of ES6, or you need to convert ES6 into ES5 (or lower) using a tool such as Babel. If you want to learn how to get set up with ES6, check out my post on how to get started with ES6. It has all the information you need to get going, so in this article I’ll focus on the features and their benefits.

let and const

The let keyword defines a block-scoped variable. Block-scoped means the declaration is only available within a so-called “block”. Compare how it behaves vs the var keyword:

function foo() {
  //whenever we have curly braces in code, it defines a "block"
  {
    console.log(hi); //error, the variable is not defined

    //this is only available within this block
    let hi = 1;
  }
  console.log(hi); //output: Error, hi is not defined

  for(let i = 0; i < 10; i++) {
    //the variable `i` is only available within the for block
  }

  console.log(i); //output: Error, i is not defined
}

Swap in some vars instead of lets…

function foo() {

  {
    //with var, the variable declaration gets hoisted so we will not get an error
    //when attempting to use it before its declaration appears in code
    console.log(hi); //output: undefined

    var hi = 1;
  }
  console.log(hi); //output: 1

  for(var i = 0; i < 10; i++) {
    //the variable `i` is only available within the for block
  }

  console.log(i); //output: 10
}

Variables declared using var are also hoisted, as shown with the log statement, which can cause unexpected behavior to those unfamiliar with JavaScript’s hoisting rules. const declares a block-scoped constant. You may be familiar with constants from other languages, and here they are the same: A constant is like a variable, except you can’t change its value.

const foo = 1;
foo = 2; //error: cannot change the value of a constant

There is one small gotcha when using const. When assigning an object, you will still be able to modify its properties!

const obj = { hello: 'world' };
obj.hello = 'galaxy'; //no error!

But assigning another object, even if it has the same properties, will cause an error:

const obj = { hello: 'world' };
obj = { hello: 'galaxy' }; //error

A workaround exists for this, using Object.freeze:

const obj = { hello: 'world' };
Object.freeze(obj);
obj.hello = 'galaxy'; //this will now cause an error

(thanks Reddit user jcready for this tip)

Benefits of let

A major benefit of let is it works nicely within for-loops. One of the most common stumbling blocks for JS-beginners is the closure-within-for problem:

for(var i = 0; i < 10; i++) {
  foo[i].onclick = function() {
    console.log(i);
  };
}

Seasoned JS developers recognize this and know that the click handlers will all output 10. If we rewrite this using let

for(let i = 0; i < 10; i++) {
  foo[i].onclick = function() {
    console.log(i);
  };
}

…it now behaves as could be expected: the handlers will output the value of i from their respective iterations. To me, the behavior with let is better than var. let does everything, making var feel unnecessary. For an opposite point of view, check out Kyle Simpson’s in-depth article, for and against let.

Benefits of const

Constants are perhaps a bit less common, but const can bring many benefits when making sure your code is correct and easy to reason about. Sometimes you need to declare values in functions which should not be modified – in other words, constants – and using const there gives two benefits:

  1. The person reading the code immediately sees the variable should not be changed
  2. Changing the value will result in an error

Using const to indicate values that shouldn’t change, you also reduce the likelihood of bugs. The code cannot redeclare or change the value, guaranteeing that the value keeps its meaning. Bugs have been known to occur because another programmer accidentally changed a variable like that – using const eliminates the possibility. For example, one case is functions calling other functions to get data, or initializing helper variables. These can be declared const, as they are often not changed. Using const together with let and var, it’s easier to communicate the intent of your code, which helps to make the code self-documenting.

Computed property names

Have you ever had to write something like this?

var obj = { };
obj[prop] = 'some value';

I certainly have. In ES5 there is no way to use a variable directly in an object literal, so you need to assign it separately like above. It’s only a minor issue, but ES6 fixes it by allowing the following syntax:

var obj = { [prop]: 'some value' };

Another trick is more dynamic property names:

//this will assign to obj.foo10
var obj = { ['foo' + 10]: 'some value' };

You can put pretty much any code inside the square brackets. Not a life changing feature, but convenient in some cases.

Default parameters

A common source of confusion to those unfamiliar with JavaScript syntax tricks is the following pattern:

function hello(name) {
  name = name || 'Anonymous';

  console.log('Hi ' + name);
}

This syntax is often used to give function parameters default values. Even when you do know this syntax, it fails spectacularly when dealing with booleans, numbers or other falsy values. In other words, it would be better to avoid this pattern, but unfortunately there hasn’t been a convenient way to have default values… until now. ES6 allows us to define default values for function parameters!

function hello(name = 'Anonymous') {
  console.log('Hi ' + name);
}

The benefits should be reasonably clear:

  • Less boilerplate code to handle parameters
  • Anyone reading your code immediately sees which parameters are optional, without having reading the function body (where they might or might not be on top of the function).
  • This can be useful when refactoring, as you can change a function to have default parameters instead of removing a parameter altogether to keep better backwards-compatibility

One potential gotcha of this syntax is that variables without default parameters still receive undefined as their default, rather than throwing an error if not called with enough parameters. This is how JavaScript has always worked like, but especially for newcomers this could be a point of confusion. Passing undefined as the value for something with a default parameter defined will also use the default parameter instead of undefined. It’s better to use null to represent cases of “no value” instead of undefined, it will avoid this issue. There’s also an interesting trick that you can use with defaults to enforce required parameters. You can read about it here.

Destructuring assignment

Destructuring assignment, available in many other languages, can be a very convenient feature when dealing with objects or arrays. Let’s say we want to do this:

var name = user.name;
var email = user.email;

With ES6 we can use what’s called a destructuring assignment:

var { name, email } = user;

Alternatively, if we want to use variable names which differ from the property names…

//this declares two variables, userName and userEmail
var { name: userName, email: userEmail } = user;

Which is functionally equivalent to:

var userName = user.name;
var userEmail = user.email;

Where is this useful? A common pattern is using objects to pass around large numbers of parameters, especially if the parameters are optional. That scenario is where destructuring shines:

function complex({ name, email, phone = null }) {
  //variables `name`, `email`, and `phone` are available here
}

var user = {
  name: 'foo',
  email: 'bar',
  phone: '123456'
};
complex(user);

Note we used destructuring in the function parameter list – it also works there, and even supports defaults! By doing this, we get a number of benefits:

  • We make the properties the object parameter requires explicit. A common issue is seeing a function takes an object, but not knowing what kind of object. Now that’s solved.
  • We can have defaults. No need to check if the property is there
  • We make optional properties explicit. By providing a default for a property, anyone reading the code sees the property is optional.

Explicitly visible things make code easier to maintain, as you don’t have to guess or read the whole function to figure it out. You can do many fancy things with destructuring. For comprehensive examples, you should check Scott Allen’s post on ES6 destructuring. Be careful to not take things too far. It’s possible to make your code harder to read with too much use of destructuring:

let { address: { home: { street } } = user;

//is equivalent to:
let street = user.address.home.street;

You can probably see the example without destructuring above is much easier to understand.

Object initializer shorthand

This feature allows you to skip repeating yourself in object literals. A pattern seen in the nodejs world:

module.exports = {
  someFunction: someFunction,
  otherFunction: otherFunction
};

Sometimes you also see the same with the module pattern:

var myModule = (function() {
  /* declarations here */

  return {
    someFunction: someFunction,
    otherFunction: otherFunction
  };
})();

Using ES6’s object initializer shorthand, we can rewrite it:

module.exports = {
  someFunction,
  otherFunction
};
var myModule = (function() {
  /* declarations here */

  return {
    someFunction,
    otherFunction
  };
})();

Again a feature without huge benefits, but reducing duplication is always a good thing.

Rest and spread parameters

Rest and spread parameters introduce new syntax for functions which take an arbitrary number of parameters, or when using arrays as parameters. In ES5, to write a function taking multiple parameters (such as Array#push)..

function push() {
  var args = Array.prototype.slice.call(arguments);
  var list = args.shift();

  args.forEach(function(a) {
    list.push(a);
  });
}

In other words, we need to use the arguments object, which is not ideal. We also can’t describe the function’s ability to take any number of args very easily without using comments. This leads to confusing code. Using rest parameters in ES6, we can instead write the following:

function push(list, ...values) {
  values.forEach(function(v) {
    list.push(v);
  });
}

This code automatically creates an array of all the parameters after the first, and the array is assigned to the variable values. This is much more readable at a glance: You can immediately tell this function can take any number of args. And even better, we don’t need the boilerplate for using arguments. Spread parameters is similar:

var values = [1,2,3];
var target = [];
target.push(...values);

The syntax with ...list above is same as this:

target.push(1, 2, 3);

Although a bit situational, this can be a useful feature in some cases.

Template literals

At simplest, template literals allow easy interpolation of variables into strings, and easier multiline strings.

var name = "Björn";

var text = `Hello ${name}`;
console.log(text);

The output would be “Hello Björn” as you might guess. Multi-line strings work as follows:

var text = `Foo
bar
baz`;

The more complex side of template strings is called “tags”:

var sample = foo`Some text here`;

In the above example, foo is a so-called “tag”, which are functions that can transform the string. For example, we can define a naive text-reverse tag..

function reverse(strings, ...values) {
  var result = '';
  for(var i = 0; i < strings.length; i++) {
    result += strings[i];
    if(i < values.length) {
      result += values[i];
    }
  }
  
  return result.split('').reverse().join('');
}

var foo = 'bar';
console.log( reverse`Hello World ${foo}` );

The output is “rab dlroW olleH”. A text-reversing tag is not very useful, could it be used for something else? As an example, we could have a tag to auto-escape SQL strings:

db.query(sql`SELECT * FROM x WHERE foo = ${parameter}`);

This is only scratching the surface, but template strings are a powerful feature and I hope library authors will make use of it in the future.

Promises

Promises are a way of dealing with asynchronous code. Code using promises can make asynchronous code easier to compose, and can also avoid the common issue of “callback hell”. Let’s look at a simple example to show why promises can be useful vs. callbacks. Say you have three asynchronous functions and you need to run all three, and then execute another function:

//for sake of example, we're just using setTimeout. This could be any asynchronous action as well.
function asyncA(callback) { setTimeout(callback, 100); }
function asyncB(callback) { setTimeout(callback, 200); }
function asyncC(callback) { setTimeout(callback, 300); }

asyncA(function(resultA) {
  asyncB(function(resultB) {
    asyncC(function(resultC) {
      someFunction(resultA, resultB, resultC);
    });
  });
});

Compare to an implementation using promises:

function promiseA() { return new Promise((resolve, reject) => setTimeout(resolve, 100)); }
function promiseB() { return new Promise((resolve, reject) => setTimeout(resolve, 200)); }
function promiseC() { return new Promise((resolve, reject) => setTimeout(resolve, 300)); }

Promise.all([promiseA(), promiseB(), promiseC()]).then(([a, b, c]) => {
  someFunction(a, b, c);
});

Promises allow easily composable asynchronous functions, without creating a callback-pyramids like in the first example. We do need a bit more code to create the promise in the first place, but if our asynchronous functions were longer, it wouldn’t be such a visible difference. This is only one of the advantages of using promises, and it’s a very broad topic. If you are unfamiliar with promises and their benefits, I recommend reading Kyle Simpson’s take on promises in his book You Don’t Know JS (free to read online). Promises can simplify asynchronous code a lot, but it can be hard to use them to their full potential. Check out my list of the best resources to learn about Promises for more.

Arrow functions

Arrows is a new syntax for functions, which brings several benefits:

  • Arrow syntax automatically binds this to the surrounding code’s context
  • The syntax allows an implicit return when there is no body block, resulting in shorter and simpler code in some cases
  • Last but not least, => is shorter and simpler than function, although stylistic issues are often subjective

The syntax is quite flexible:

//arrow function with no parameters
var a1 = () => 1;

//arrow with one parameter can be defined without parentheses
var a2 = x => 1;
var a3 = (x) => 1;

//arrow with multiple params requires parentheses
var a4 = (x, y) => 1;

//arrow with body has no implicit return
var a5 = x => { return 1; };

this binding

How often do you see something like this done in JS?

var self = this;
el.onclick = function() {
  self.doSomething();
};

This pattern crops up occasionally, especially in less experienced dev’s code. The solution is to use bind to fix this in the function, but it’s a bit verbose. With arrows, we can instead just do this:

el.onclick = () => this.doSomething()

Implicit return

The arrow syntax allows two different styles… With a statement body:

el.onclick = (x, y, z) => {
  foo();
  bar();
  return 'baz';
}

//equivalent to:
el.onclick = function(x, y, z) {
  foo();
  bar();
  return 'baz';
}.bind(this);

A statement body allows multiple statements as shown above. An arrow function with an expression body looks like the example we saw earlier:

el.onclick = (x, y, z) => this.doSomething()

//equivalent to
el.onclick = function(x, y, z) {
  return this.doSomething();
}.bind(this);

An expression body allows only a single expression, and has an implicit return. This means it’s great for functional-style code, for example when using Array#map or Array#filter

//ES5 style
var names = users.map(function(u) { return u.name; });

//ES6 style
var names = users.map(u => u.name);

ES6 modules

The CommonJS module specification has become increasingly common. First, Node.js adopted it, starting the downfall of the competing AMD and require.js module specifications. Recently tools like Browserify and Webpack have made CommonJS modules the best choice for JavaScript code running in the browser as well. The native support for ES6 modules is still lacking, but thanks to the tools mentioned above, we can easily use the ES6 modules with our JS code. Here’s a comparison of how ES6 modules are defined vs CommonJS modules:

export const magicNumber = 42;

export function amazingFunction() { return 'the magic number is ' + magicNumber; }

//vs CommonJS...
const magicNumber = 42;

function amazingFunction() { return 'the magic number is ' + magicNumber; }

module.exports = { magicNumber, amazingFunction };

The ES6 module version allows us to write our module with some less repetition – anything we define as being exported is also available within the module itself. In the example with CommonJS, we need to define the value first, and then separately define the export using module.exports. The syntax for importing modules is also slightly more concise compared to CommonJS:

import { magicNumber } from './my-module';

//vs CommonJS...
const { magicNumber } = require('./my-module');

There’s a number of additional options available with ES6 modules. Exploring ES6’s chapter on Modules is a good resource to learn more.

Iterators and Generators

Another new feature is iterators: you can make “iterable” objects, as in similar to how you can iterate through arrays using loops. You do this either with a new syntax called symbols, which allows for special object properties with special functionality, or with another new feature called generators. Generators can yield values. The function’s execution pauses at the yielded value, and the next time the generator is called, it resumes from where it left off. This can also be used for dealing with asynchronous code in another interesting way, but I’ll talk about that in another article as it’s a big topic on its own. For working with iterators, ES6 also provides a new looping syntax called for-of:

var arr = [1, 2, 3];
for(var value of arr) {
  console.log(value);
}
//output: 1, 2, 3

This is similar to how foreach-loops work in other languages. Another similarity with foreach is that this also works with iterators, so you can use your own iterable objects with for-of. Iterators are mainly useful for library authors. It could be useful to offer an iterator-based interface for a library, but in most circumstances you won’t need them.

In closing

I’m sure you’re asking now “What about the new class syntax! ES6 has the new class syntax, right?” – well, that’s correct. However, the class syntax is only syntactic sugar over JavaScript’s prototypal OOP. It doesn’t change anything about how the system works, it merely provides some convenience if you prefer that style. There aren’t really any benefits from the syntax over just working with plain objects. The only case where the class syntax could be useful is with heavy inheritance, but it’s often better to use composition instead. This is a big topic on its own, and outside the scope of this article. Overall the new features in ES6 provide a number of benefits especially for larger applications. If you don’t need to support older browsers, then you’ll have a fairly easy time since ES6 features are well supported across recent browsers. For older ones, you may need to use Babel to compile the code into something that works. Kangax’s ES6 compatibility table is a good resource to use if you’re not sure what you need.

About the Author:

Teamwork with the Compiler: An Interview with a Functional Programmer

March 9th, 2017

Peter Jones is a freelance software developer, instructor for DevelopIntelligence/appendTo, and has an incredible assortment of bow ties. He spends his working hours giving in-person software training for DevelopIntelligence, developing software for clients, and contributing to open source projects. Peter is passionate about functional programming and prefers to work in purely functional languages. We spoke to him about functional programming to understand more about its dramatic rise and appeal.

DevelopIntelligence/appendTo: Hello Peter. Tell us a bit about yourself.

Peter Jones: My background is first and foremost in software engineering. I split my time right now, fifty percent of my work week is writing software as a contractor and then the other fifty percent of the time I spend in training related activities. So I’m half training, half coding.

I’ve been playing with software ever since I was a kid and I’ve been doing it professionally for over twenty years. As far as training goes, I’ve been doing that for over ten years, I actually learned some of the basic skills for teaching while I was in the Air Force. Outside of training, the other big part of what I do is I’m a big advocate of open source and I spend a lot of time contributing to open-source projects.

DevelopIntelligence/appendTo: Cool! Which projects have you worked on in the last year?

Peter Jones: There are a lot of them. One of the projects that I’m probably spending the most time with right now is XMonad. It’s a tiling window manager for Linux. The other thing that I’m just a huge fan of and I’ve been slowly contributing more and more code to is a Linux distribution called NixOS, it’s a functional programming language sitting on top of Linux. As a functional programmer, I really, really like it.

DevelopIntelligence/appendTo: In your freelance work, what are you primarily working in?

Peter Jones: It really varies. I could say that last year it was about 80% functional programming, specifically in Haskell, and about twenty percent in Ruby.

DevelopIntelligence/appendTo: What do you like or not like about the balance between teaching and coding?

Peter Jones: I really, really like teaching but I don’t think I can do it full time. It is a big emotional drain on me because I’m an introvert. I fit really nicely into that stereotype of the software developer who likes to be a hermit and away from everybody. So 50/50 is the perfect balance for me.

I am very, very passionate about learning and teaching highly motivates me to learn things inside and out. It forces you to anticipate your student’s needs and the questions that will come up. I also love socializing with other engineers and getting to have a conversation about different technologies.

But I also really like the times when I’m not teaching because I’m actually kind of practicing what I preach. I’m in the trenches working with the stuff I’m teaching on.

DevelopIntelligence/appendTo: It sounds like one of your main specialities is functional programming. What is your take on it from both a coding and teaching perspective?

Peter Jones: The whole realm of functional programming is really big. It’s a big spectrum and there’s a corner of it where I like to hang out. I like the area of strongly typed and purely functional languages.

The key point of functional programming really comes down to software quality and confidence that what you’re writing is going to work correctly. That it won’t have a lot of bugs that plague other languages. We all make mistakes and it’s nice to have tooling to catch those mistakes for us. That’s what strongly typed purely functional languages bring to the table.

DevelopIntelligence/appendTo: Could you give some examples of this?

Peter Jones: These languages (like Haskell or PureScript) don’t have a lot of the troublesome features that other mainstream languages have. Purely functional languages approach programming totally differently and they don’t have things like the NULL type. They don’t have values that can really cause a lot of havoc in production systems because they sneak into your program at runtime. Non-functional languages really put a big burden on the software developer to make sure they are handling errors and uncertainty in their code. They have to check at every possible moment that a NULL hasn’t snuck in.

These truly functional languages don’t even have that value; it’s just something you don’t have to worry about it at all. Instead of having that feature, they have a type system that says “hey, you’re going to call this function and it may return an error and you must deal with it.”

When the compiler is producing a binary, it will look over your program and tell you places where you’re invoking a function that may fail and not dealing with it correctly. The compiler says, “I’m not going to make the binary for you until you fix this.”

DevelopIntelligence/appendTo: Let’s talk about Haskell, in particular. What has it been like learning it and working with it?

Peter Jones: When I decided to learn Haskell, I kind of had this chip on my shoulder that this won’t be that big of a deal. At that point I could learn any programming language in 24-48 hours pretty easily. I just needed to learn the syntax because I have so many languages under my belt and usually from one language to another, they’re about eighty percent similar. From C++ to Java they’re probably ninety percent similar. From Java to Ruby, same thing. You just have to learn the syntax and a couple of idioms. But for the most part the languages operate very similarly.

But this doesn’t apply to the functional languages. They have a totally different idea of what programming is and what you can do with the programming language. It’s almost like having to relearn programming from scratch. There is almost a kind of wall for people to approach these languages.

With Haskell in particular, the challenge has to do with the fact that the language was kind of born out of an academic environment. And so that kind of leaves a bad taste in engineers mouths when they hear about the language and approach it. They think, “Oh this is just some kind of academic experiment”.

But there’s a lot of industry support as well. Companies like Facebook are using Haskell in small doses There are a lot of financial companies using Haskell and that’s because you end up working with a high quality product at the end of the day. You just have to be willing to adjust your way of approaching the problem. When you use a purely functional language with the strong type system, it means that you can’t just sit down at your keyboard and hack out something and get to some kind of working product. Instead, you actually have to take the time to think about what problem you are solving and how do you want to solve it. You have to think a lot more about the kind of problems you are going to encounter while solving this problem.

It’s really interesting to work in a language that forces you to think more. That’s what these languages do. They force you to work hand in hand with the compiler, the tool that’s going to produce the binary for you. Functional programming makes you work with the compiler closely to get to the end result.

You’re telling the compiler, “This is the part I’m trying to come up with.” The compiler is telling you if you’re there or you’re not there or if you’re going about it the wrong way. It’s kind of this team work you have with this other program running.

DevelopIntelligence/appendTo: Very interesting. Where does Elm come into play? How did Elm come about?

Peter Jones: Elm comes from taking the lessons that have been learned about functional programming and then applying them to a web development. Elm is a replacement for using JavaScript to write web applications. Elm allows you to use a purely functional typed language and then the Elm compiler turns that all into JavaScript, HTML, and CSS. This lets you work with a competent strong language instead of a real loosey-goosey dangerous language like JavaScript.

DevelopIntelligence/appendTo: What is the mental switch that you have to make when you switch from a functional language back to a more object oriented or prototypal language?

Peter Jones: When I go into other languages, I feel like I’m in dangerous territory. I feel I’ve been given enough rope to hang myself and I’m almost encouraged to hang myself in languages like Ruby or C++ and especially in JavaScript. I have to be on my tip toes ensuring that I’m doing the right thing because now I don’t have this compiler or type system that’s helping me.

Sometimes, especially in languages like JavaScript, I feel like it’s actually working against me and I have to go on my own and find the best path. So the mental shift is real. The confidence in my code quality goes way down and I have to compensate for that by writing lots and lots of tests and slowing down and really thinking about all the side effects of the code that I’m writing. I have to think “What could possibly go wrong?” Because the tooling is just not there to give me confidence that the end product is going to work correctly.

Haskell and these other languages have helped me become a better programmer because I’m way more thoughtful then when I’m using these sloppier languages. I’m considering all the pitfalls as I’m writing. Before I knew Haskell, I’d just write the code and run some tests and think that I did the best I could. Now I’m realizing there’s a whole lot more I could be doing and a lot more I need to be thinking about as a programmer.

DevelopIntelligence/appendTo: If it were possible, would you switch most of what you’re doing to work in purely functional languages?

Peter Jones: Absolutely. If I have a contract and the contract involves, JavaScript, my very first question is, “Hey can we use Elm or can we use PureScript?” Both of those languages are purely functional and compile into JavaScript. And I think there’s a really easy and compelling argument to make from the quality and maintainability standpoint.

DevelopIntelligence/appendTo: If you were teaching functional programming to non-functional programmers, what are some steps or tips or ideas on how would you approach the task of having them understand the functional paradigm?

Peter Jones: The way I would approach it is to gently introduce people to the idea and peel back the layers of the onion slowly one at a time. Show them how to accomplish some kind of everyday programming tasks in the language without really describing what’s all going on in the background, especially when it comes to the type checking. Show them how to accomplish some of the same tasks and then once they are able to at least write a few small programs in these purely functional languages, then go back and say, okay let’s talk about why this is happening, why we did this, what is it providing for us, why do these things have weird names.

Because they come from mathematics and not from computer science.

I would help them to understand what are the points of these things and what’s actually going on behind the scenes to make this program work? Give them that kind of more global view of the language and their run time.

And then for tips: find a mentor, chat room, or a community for help when you get stuck. After you’ve tried to work on a problem and if you’re just hitting your head against the wall, then turn to your mentor for help.

About the Author:

A Primer on JavaScript Promises

February 21st, 2017

In JavaScript, a promise is simply a placeholder for a future value. It’s a piece of code that promises to return a value at some point in time. The beauty of promises is that they provide an easy and elegant way to handle asynchronous operations (e.g., setTimeout, AJAX calls, etc.). In the following article, I’ll show you the basic setup for JavaScript promises. I’ll also show a couple of examples of their typical operation. You’ll find the information useful, I promise!

Basic Setup

A promise looks like this:

See the Pen GryKYG by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Things to note:

  1. A promise is instantiated with a call to the Promise constructor
  2. Here, the promise is assigned to a promise variable
  3. A callback function is passed to the promise with the parameters resolve and reject
  4. Asynchronous code is executed within the promise’s callback function
  5. Good results are passed to the promise’s then method by calling resolve
  6. Bad results (and errors) are passed to the promise’s catch method by calling reject
  7. A callback is used in then to handle the good data
  8. A callback is used in catch to handle the bad data

 

Examples

Here’s an example of a promise in action:

See the Pen RKxbOJ by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Notice how the asynchronous setTimeout code is wrapped in the promise and it’s callback function, and how it returns a value 2 seconds after the test function is called. The conditional logic within the promise/callback is used to determine whether resolve or reject gets called. The value resulting from the asynchronous code is passed to either then or catch through resolve or reject. If an error were to occur, it would also be passed to reject.

Additionally, worth noting is the common terminology used with promises:

  1. Before a promise receives a value, it is said to be pending
  2. Once a promise receives a value, if the value meets acceptance criteria, it’s fulfilled
  3. Once a value is received, if it doesn’t meet acceptance criteria, it’s rejected

 

Here’s one more example using AJAX:

See the Pen GryRBb by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Notice how the AJAX code is wrapped in an instance of a promise. If everything goes well with the AJAX request, the returned value is resolved and sent to the promise’s then method for handling. If something goes wrong and the response comes back with something other than is intended or if there is an error, then that data will be picked up by the promises catch method, with the error data eventually being logged to the console. Promise, then, catch; it’s as easy as that.

Hopefully you found this information on JavaScript promises useful. Remember that promises offer a clean way to work with asynchronous operations. They are constructed with a call to the Promise constructor. They have then and catch methods that are used to handle results; the then method handles good values once they’ve been fulfilled/resolved, and the catch method handles bad data or errors.

About the Author:

A Primer on ES2017 Async and Await

February 11th, 2017

As the year 2016 draws to a close, attention is now turning to what will emerge from 2017, with Javascript as much as anything. The language is undergoing a massive evolution now, increasingly taking on characteristics that make it attractive as a full stack environment.

The ES2017 (ES8) stack is already now being implemented in both Node and several modern browsers, addressing many of the more complex issues of web development including better ways of dealing with asynchronous coding. This piece will give a short primer on working with the new ES2017 features Async and Await.

Async and Await

More than almost any other language, JavaScript has struggled with a seemingly simple problem – how do you keep interfaces responsive when you have to fetch (or send) contents over a data socket across the web? The first solution to that was to write polling routines to activate a setTimeout or setInterval call, then returning a flag state that indicated a given transfer was complete. With the advent of AJAX calls in the late 1990s, this functionality was relegated to a specific object, the XmlHttpRequest object, and later eventually subsumed in jQuery oriented ajax(), get() and post() functions.

This, in turn, introduced the notion of asynchronous callbacks into Javascript – passing a function as an argument to another asynchronous function with a predetermined set of parameters. Such callback functions would then be invoked once either the data had completed transferring or an error had occurred (in which cases a different function would be passed for cleaning up the action).

One problem became quickly evident with this approach. The resulting callback functions themselves often needed to push the resuting data to another function, which would require another callback, and eventually the resulting code became hideously deep and complex.

The first solution to this problem was to implement a construct called a promise. A promise was a deferred callback object that was implemented initially in ES2015, then refined in ES2016. A promise was a wrapper object that held the callback function(s). When the invoked asynchronous function completed, then it would return a resulting object that could then be passed into a new promise, resulting in a promise chain.

This construct was better, but could still end up being too verbose, especially when what you needed was data from multiple sources independently. The async identifier, along with the await keyword, is the ES2017 solution to that particular problem. As a simple example , first create a promise, in this case a promise of a function that returns a value after a specified number of seconds:

function resolveAfterInterval(x,t) {
 return new Promise(resolve => {
  setTimeout(() => {
   resolve(x * x);
  }, t * 1000);
 });
}

Here, the function resolveAfter interval takes two parameters, a value that will be squared, and the time in seconds. The function creates a new promise around a function (internally called resolve()) that in turn calls a setTimeout function. The resolve function is itself just a placeholder that returns whatever is passed into it, here the square of the number. The t parameter in turn is used to set the number of seconds before the function returns.

The await keyword is applied to a function or variable to indicate that it should await the completion of the promise before passing the results of that promise. If the await is passed on the variables, then the return statement is invoked once the last of the variables are known, here at three seconds.

async function distance1(x) {
 var a = resolveAfterInterval(20,2);
 var b = resolveAfterInterval(30,3);
 return Math.sqrt(Math.pow(x,2) + Math.pow(await a,2) + Math.pow(await b,2));
}
distance1(10).then((v)=>console.log(v))

Note that that await serves very much the same purpose in an asynchronous function that yield does for a generator (and they use many of the same mechanics under the hood). Here, the output will return only once the longest promise’s interval completes, at 3 seconds.

This is a little different from the situation where the awaits is applied to the functions themselves:

async function distance2(x) {
 var a = await resolveAfterInterval(20,2);
 var b = await resolveAfterInterval(30,3);
 return Math.sqrt(Math.pow(x,2) + Math.pow(a,2) + Math.pow(b,2));
}
distance2(10).then((v)=>console.log(v))

In this example, the first await won’t return until after two seconds, while the second await won’t return until three seconds after the first one is satisfied (or five seconds after the code starts). This occurs because the await acts like an asynchronous block – in the second example, the following statement won’t occur until after the initial function’s promise is returned, but in the first example, the return statement executes once the variables have been assigned.

Using await is actually quite valuable in situations where you want an action to occur once all of the data is available from all sources, but not a moment after. Ordinary chaining of promises is almost as bad as synchronous processing (since you’re dependent upon waiting for one promise to complete before a second one can start, as the second example shows), but with the async and awaits keywords you can reduce this wait only to that of the longest single process.

Summary

ES 2017 is the culmination of an upgrade cycle that has significantly changed the flavor of the Javascript language, bringing it more in line with contemporary functional languages such as Haskell or Scala. The language that has emerged is becoming quite powerful and expressive. At the same time, there is a huge amount of innovation occurring with various libraries such as mobX, React and elsewhere, and these in turn are becoming grist for strengthening the core language to better reflect these innovations.

About the Author:

Advanced JavaScript ES2015 Template Strings with Tagged Templates

February 1st, 2017

If you’ve paid any attention to the discussions about ES2015/ES6 that have been going on over the past couple years, you should already know about template literal strings:

`This string starts and ends with a backtick and can have expressions, e.g. 5 + 5 = ${5+5}.

It can also have multiple lines without any odd "hacks".`

This in itself is an extremely useful tool that can simplify how we work with strings dramatically, but there is a little-known feature that came along with the template strings that can take them to an entirely different level of usefulness: tagged template literals.

Tagged Template Literals

A tagged template literal is a template literal (as you’ve already seen) that is preceded by a tag. A tag is a function that receives all the pieces of the string that you created via the template literal and returns something that should be based on the string. Here’s a simple (and incomplete) example to help you understand:

// Some dummy data... just I just call myself a dummy?
let user = {
    firstName: "Joseph",
    lastName: "Zimmerman",
    nickname: "Zim"
}

// Define the tag (definitely doesn't need to be called "tag")
function tag (...args) {
    // do something with those args
    // return something
}

// prefix with `tag` and foo will be set to whatever tag returns
let foo = tag`My name is ${user.firstName} ${user.lastName}, but my friends call me ${user.nickname}.`

This looks very strange to those who aren’t acclimated. You wouldn’t put the name of a function right in front of any old string (e.g. myFunc"a string") and expect anything to happen other than a syntax error, right? Well, it works just fine with template strings. The interesting thing here is that it ends up being a function call without using any parenthesis. Things are just getting weirder by the second!

So the next question on your mind is probably, “what arguments does the tag function get called with?”, right? Well, that’s what I was wondering when I first looked at these, so that’s what we’ll look at next. The first argument is an array of each of the pieces of the string that aren’t template substitutions (the expressions surrounded by ${ ... }) . The rest of the arguments are each of the template substitution values.

Once again, I think an example will help explain things:

function tag (stringBits, val1, val2) {
    console.log(stringBits) // => ["My name is ", " ", "."]
    console.log(val1) // => "Joseph"
    console.log(val2) // => "Zimmerman"
}

tag`My name is ${user.firstName} ${user.lastName}.`

I’m a little disappointed that you only see the interpolated values of the expressions and that there’s no way to get access to the literal expression so that the tag functions can allow an additional way of handling the interpolation. I’m sure there’s a good reason, such as confusing developers when the expressions don’t end up as the same value they expected.

Anyway, as you can see, all of the string parts show up as an array for the first argument. Even if there’s no characters between certain parts of the string, you’ll end up getting empty strings in that array, For example:

function tag(stringBits) {
    console.log(stringBits) // => ["test", "", ""]
}

tag`test`

See how we received 2 empty strings in that array. The first one is the characters between the two expressions and the second one is at the end of the string, after the second expression.

Also, not that every interpolated value is passed into the tag function as a separate arguments. This would be a big pain in the rear end, but since we’re using ES2015 anyway, we can use rest parameters to group all of those arguments into an array, like this.

function tag (stringBits, ...values) {
    console.log(stringBits) // => ["My name is ", " ", "."]
    console.log(values) // => ["Joseph", "Zimmerman"]
}

tag`My name is ${user.firstName} ${user.lastName}.`

I can’t foresee any situations where this wouldn’t be the preferred way of handling those values, so we’ll stick to using the rest parameter from now on.

One last thing to note: I haven’t been completely honest about the value of stringBits (the first parameter of the tag function) in these examples. You see, stringBits is more than just an array; it also has a raw property, which is also an array of the string pieces. There’s a difference, though: if you have escaped characters in your string (e.g. "\n"), it’ll be converted to a new line in the main array, but in the raw array, it’ll show up just as you typed it, as if you had actually used "\\n". Check out the example below:

let place = "world"

function tag (stringBits, ...values) {
    console.log(stringBits)
}

tag`Hello ${place}.\nWelcome to this tutorial.`

The Chrome console would output something like this:

Array[2]
    0: "Hello ",
    1: ".↵Welcome to this tutorial.",
    length: 2
    raw: Array[2]
        0: "Hello ",
        1: ".\nWelcome to this tutorial"
        length: 2

See how in the main array there is a "↵" representing the new line, whereas in the raw array we still see the "\n". If you’re looking for the raw characters that the developer writes then this can be useful. It’s also worth noting, though, that if you simply want to create a tag so that you can get the raw string, then don’t waste your time. There is a built-in tag for that: String.raw.

String.raw`Hello ${place}.\nWelcome to this tutorial.`
// => "Hello world.\nWelcome to this tutorial."

Just as a quick exercise, let’s recreate the normal template literal behavior with our own tag function:

function tag(strings, ...values) {
    return strings.reduce(function(combined, string, i) {
        return combined + string + values[i]
    }, "")
}

Turns out it’s as simple as strings[0] + values[0] + strings[1] + values[1]..., which we accomplish with reduce so that we don’t need to worry about how many parts are in the string.

Applications

So what kind of applications are there for this? How can you use tagged template literals in a helpful way? Well, I couldn’t think of anything special, but some others in the community have. The first example is html-tagged-template, which allows you to feed a string of HTML into it, and the tag will actually spit out DOM nodes that match your HTML.

html`

 

 

 

Hello

 

 

 

`

This will return the entire hierarchy of DOM nodes without resorting to innerHTML nonsense or a ton of node creation and appending. I’d check out the project to see how it might help you, though something like React’s JSX might be a better solutions because a lot of the parsing is handled by the pre-processor rather than the browser.

Speaking of React, there is another powerful use for tagged template literals called styled-components that simplifies how you create base components and style them by allowing you to just specify the CSS as a template literal to the tag from styled-components. For example:

import React from 'react';
import styled from 'styled-components';

// Create a <Title> react component that renders an <h1> which is centered, palevioletred and sized at 1.5em
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

// Create a <Wrapper> react component that renders a <section> with some padding and a papayawhip background
const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

function HelloWorld () {
  return (
    <Wrapper>
      <Title>Hello World, this is my first styled component!</Title>
    </Wrapper>
  );
}

export default HelloWorld;

This gives you a few React components:

  • Title, which is an H1 tag styled with the CSS provided in the template literal string
  • Wrapper, which is a SECTION tag styled with the CSS provided in the template literal string.
  • HelloWorld, which composes the other two components

You can go here to see this in action and fiddle around with it. Of course, you’re not obligated to try it; I just wanted to give you some examples of how tagged template literals can be used to do some powerful things. If you have any questions about tagged template literals or interesting ideas of how you could use them, drop them in the comments.