Monday, February 13, 2017

What New ES6/7 Has To Offer?

This post will give you a quick introduction to ES6 (aka ECMAScript 2015). If you don't know what is ES6, it’s a new JavaScript implementation. If you haven't taken a look at ES6/7 yet you're missing out on some amazing advances to the JavaScript language.

Some of the important features of ES6/7 are below:
• let, const
• Template Strings/literals
• Arrow Functions
• Classes
• Object Destructuring
• Concise Objects
• Modules
• Default Parameters
• Native Promises
• Async Await
• Spread Operators
• Rest Parameters

Let + Const
In ES5, you declare variables via var. Such variables are function-scoped, their scopes are the innermost enclosing functions. In ES6, you can additionally declare variables via let and const. Such variables are block-scoped, their scopes are the innermost enclosing blocks.

let is the new var and block-scoped: they only exist in the block they are defined in.
var num = 0; //globally scoped

for (let i = 0; i < 10; i++) { //i is block scoped
  num += i;
  console.log('value of i in block: ' + i);

console.log('Is i defined here?: ' + (typeof i !== 'undefined')); //Is i defined here?: false 

Constants (also known as "immutable variables"), i.e., variables which cannot be re-assigned new content. const is single-assignment. const works like let, but the variable you declare must be immediately initialized, with a value that can’t be changed afterwards.
const foo;
    // SyntaxError: missing = in const declaration

const bar = 123;
bar = 456;
    // TypeError: `bar` is read-only

Template Strings/literals
Template literals are a new feature in ES6 to make working with strings and string templates easier. Template strings provide syntactic sugar for constructing strings. You wrap your text in `backticks` and you'll get the features described below.
• They can be multi-line. Finally!
• You can interpolate variables in them
• You can actually interpolate using any kind of expression, not just variables
• You can construct raw templates that don't interpret backslashes
// Basic literal string creation
`This is a pretty little template string.`

// Multiline strings
`In ES5 this is
 not legal.`

// Interpolate variable bindings
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

// Unescaped template strings
String.raw`In ES5 "\n" is a line-feed.`

var today = new Date()
var text = `the time and date is ${today.toLocaleString()}`
// <- 'the time and date is 8/26/2015, 3:15:20 PM'

Arrow functions
Fat arrow functions, also known as just arrow functions are a brand new feature in ECMAScript 2015 (formerly ES6). Arrows are a function shorthand using the => syntax. Arrow functions serve two main purposes: more concise syntax and sharing lexical this with the parent scope. Arrow functions behave differently than traditional JavaScript functions in a number of important ways:
• Lexical this binding – The value of this inside of the function is determined by where the arrow function is defined not where it is used.
• Not newable – Arrow functions cannot be used a constructors and will throw an error when used with new.
• Can’t change this – The value of this inside of the function can’t be changed, it remains the same value throughout the entire lifecycle of the function.
var reflect = value => value;

// effectively equivalent to:

var reflect = function(value) {
    return value;
When there is only one argument for an arrow function, that one argument can be used directly without any further syntax. The arrow comes next and the expression to the right of the arrow is evaluated and returned. Even though there is no explicit return statement, this arrow function will return the first argument that is passed in.

If you are passing in more than one argument, then you must include parentheses around those arguments. For example:

var sum = (num1, num2) => num1 + num2;

// effectively equivalent to:

var sum = function(num1, num2) {
    return num1 + num2;

The sum() function simply adds two arguments together and returns the result. The only difference is that the arguments are enclosed in parentheses with a comma separating them (same as traditional functions).

When you want to provide a more traditional function body, perhaps consisting of more than one expression, then you need to wrap the function body in braces and explicitly define a return value, such as:
var sum = (num1, num2) => { return num1 + num2; }

// effectively equivalent to:

var sum = function(num1, num2) {
    return num1 + num2;
You can more or less treat the inside of the curly braces as the same as in a traditional function with the exception that arguments is not available.

Because curly braces are used to denote the function’s body, an arrow function that wants to return an object literal outside of a function body must wrap the literal in parentheses. For example:
var getTempItem = id => ({ id: id, name: "Temp" });

// effectively equivalent to:

var getTempItem = function(id) {

    return {
        id: id,
        name: "Temp"
The concise syntax for arrow functions also makes them ideal as arguments to other functions. For example, if you want to sort an array using a custom comparator in ES5, you typically write something like this:
var result = values.sort(function(a, b) {
    return a - b;
That’s a lot of syntax for a very simple procedure. Compare that to the more terse arrow function version:
var result = values.sort((a, b) => a - b);
The array methods that accept callback functions such as sort(), map(), and reduce() all can benefit from simpler syntax with arrow functions to change what would appear to be more complex processes into simpler code.

Rest of the topics are coming soon.

References: Understanding ECMAScript 6 arrow functions
Learn ES2015
ES6 Template Literals in Depth

Tuesday, February 7, 2017

Automate Your Tasks Easily with Gulp.js Part 2

Determining Folder Structure
Gulp is flexible enough to work with any folder structure. You'll just have to understand the inner workings before tweaking it for your project.

source is the folder where we will do our work.
assets/stylesheets/style.css will be created by gulp when we process and combine our SASS files in source/scss.
The assets/javascript/bundle.js file will be created by gulp when we minify and combine all our JS files.

Writing Your First Gulp Task
Before we get right into the code I think it's very important to mention that gulp only has 4 top level functions.
gulp.task defines your tasks. Its arguments are name, deps and fn.

gulp.task('task-name', function() {
  // Stuff here

gulp.task('dependentTask', ['task-name'], function() {
  //do stuff after 'task-name' is done.
'task-name' refers to the name of the task, which would be used whenever you want to run a task in Gulp. You can also run the same task in the command line by writing gulp task-name.

gulp.src points to the files we want to use. It's parameters are globs and an optional options object. It uses .pipe for chaining it's output into other plugins.

gulp.dest points to the output folder we want to write files to.

gulp.src and gulp.dest used to simply copy files looks like:
gulp.task('copyHtml', function() {
  // copy any html files in source/ to public/
}); method that checks to see if a file was saved. like gulp.task has two main forms. Both of which return an EventEmitter that emits change events. The first of which takes a glob, an optional options object, and an array of tasks as it's parameters.
// Gulp watch syntax'files-to-watch', ['tasks', 'to', 'run']); 
If we want to watch all javascript files and run the jshint task whenever a javascript file is saved, we just have to replace files-to-watch with the source/javascript/**/*.js, and ['tasks', 'to', 'run'] with ['jshint'].'source/javascript/**/*.js', ['jshint']);
In the above code block, when any files in the source/javascript subfolders that have an extension of .js change, then the task jshint will be run against those files.

Once gulp is installed we have to give it some instruction so it knows what tasks for perform for us. But, first, we need to figure out exactly what tasks we need to run in our project.
Lint our JavaScript(check for errors) using jshint. We’ll also need a reporter for jshint to make the output nicely formatted and color coded.
Compile our Sass files.

Install Required Plugins
$ npm install --save-dev gulp-jshint jshint-stylish gulp-sass
This will install all of the plugins we will need and add them to our devDependencies in our package.json file like we did when we installed gulp.

Now we’ll add the lint task to our gulpfile.
/* File: gulpfile.js */

// grab our packages
var gulp   = require('gulp');
var jshint = require('gulp-jshint');

// define the default task and add the watch task to it
gulp.task('default', ['watch']);

// configure the jshint task
gulp.task('jshint', function() {
  return gulp.src('source/javascript/**/*.js')

// configure which files to watch and what tasks to use on file changes
gulp.task('watch', function() {'source/javascript/**/*.js', ['jshint']);
So lets step through what we’ve done.
We’ve rewritten our default task to have the watch task as dependency. What this means is that running
$ gulp
will run the watch task.

Now lets look at the new jshint task. It sources any .js files that exist in source/javascript or any of it’s subdirectories. So a file at source/javascript/courage.js would be picked up for the task just as well. These files are then passed into our gulp-jshint plugin, which then passes it into the stylish reporter to give us the jshint results.

We can run this task by doing:
$ gulp jshint

Alright, now what about that watch task. It's simple actually, if a change is detected in any of our javascript files, it runs the jshint task.

Now we’ll add the compile SASS task to our gulpfile.
Sass serves as a way to extend CSS giving support for variables, nested rules, mixins, inline imports, and more. For sass compilation we’ll use gulp-sass.
/* file: gulpfile.js */

var gulp   = require('gulp');
var jshint = require('gulp-jshint');
var sass   = require('gulp-sass');

/* jshint task would be here from above */

gulp.task('build-css', function() {
  return gulp.src('source/scss/**/*.scss')

// define the default task and add the watch task to it
gulp.task('default', ['watch']);

/* updated watch task to include sass */

gulp.task('watch', function() {'source/javascript/**/*.js', ['jshint']);'source/scss/**/*.scss', ['build-css']);
We can run this task by doing:
$ gulp build-css

We’ve only scratched the surface of gulp. Gulp can be as complex or as simple as you need it to be, and because it’s just code you can do just about anything you want as a task.

Sources and Ref:

Wednesday, January 18, 2017

Automate And Enhance Your Workflow With Gulp Part 1

Gulp is a streaming build system, by using node's streams file manipulation is all done in memory, and a file isn’t written until you tell it to do so. In short, Gulp is a task runner which uses Node.js.

Much like Grunt, Gulp is a javascript task runner. Gulp however prefers code over configuration. Being that your tasks are written in code, gulp feels more like a build framework, giving you the tools to create tasks that fit your specific needs.

Enough theory — let's start using Gulp.

Step 1: Installing Node.js
You need to have Node.js (Node) installed onto your computer before you can install Gulp. Node.js can be downloaded for Windows, Mac and Linux at Once your download completes, run that application and you should be all ready to go.

Once installed, open a command prompt and enter:
node -v
Again, this should return the version number on the next line. Now, let's do the same for npm.
npm -v
Again, this should return the version number on the next line. If you didn't get a response, then it may mean that Node didn’t install correctly or you may need to restart your command line application.

Step 2: Installing Gulp
Now, let's meet npm and install Gulp. npm is a package manager for Node that will enable you to install additional modules for use in your projects from the command line.

We can now install Gulp using npm, jump back to your command-line application and type:
$ npm install -g gulp
The npm install command we've used here is a command that uses Node Package Manager (npm) to install Gulp onto your computer. We'have add a -g flag to ensure Gulp is available globally for any project.

Verify that Gulp has installed the following command:
gulp -v
Like before, this should return the version number on the next line of your command-line.

Step 3: Navigate To Your Project Directory And Install Gulp Locally
Now that we have met our command-line interface and know how to communicate with it, our next step will be navigating to your project directory. This will likely be different for each person, but as an example this is what I would type to navigate to my local project:
Anup:~ anup$ cd /Applications/MAMP/htdocs/my-project
Once you have made it to your project directory - let's run a quick npm command to initialize our package.json file.
Anup:my-project anup$ npm init
This will prompt us to answer a few questions about our project. Once completed, it will create a file in the root directory of the project called package.json which will provide information about the project and its dependencies as shown in figure below:.

Once the package.json file is created, we can install Gulp locally into the project by using the following command:
Anup:my-project anup$ npm install gulp --save-dev
We've added --save-dev, which tells the computer to add gulp as a dev dependency in package.json as shown below.

If you check the project folder when the command has finished executing, you should see that Gulp has created a node_modules folder. You should also see a gulp folder within node_modules as shown below.

We're almost ready to start working with Gulp. Before we do so, we have to be clear on how we're going to use Gulp for the project, and part of that is deciding on a directory structure.

Next tutorial(Part 2), we will go through Directory Structure for the project and write the first GULP task.

Automate Your Tasks Easily with Gulp.js
Getting Started with Gulp

Wednesday, November 2, 2016

How to Fix Dashed Border Not Showing Problem In Firefox?

The following code to generate dotted border will not work in Firefox browser.
  <table border="0" cellpadding="0" cellspacing="0">
   <td width="35"style="width:35px;"> </td>

   <td width="530" align="center" style="width:530px;border-bottom: 1px dotted #7f7f7f"> </td>

    <td width="35" style="width:35px;"> </td>
To make it work on firefox, you can simply add the following piece of css code.
<style type="text/css">
 table {border-collapse: separate; border-spacing: 0;}
It will work now.

Monday, September 19, 2016

Tools using for my current project

Tools I am using for my current project
•  React - A Javascript library for building user interfaces
•  Cerebral - : A state controller with its own debugger
•  GraphQL - : A query language for your API
•  TypeScript - JavaScript that scales.
•  EventStore - open-source, functional database with Complex Event Processing in JavaScript
•  ECMAScript 2016 (ES2016): New version of Javascript
•  Webpack - Module bundler
•  node.js - : JavaScript runtime built on Chrome's V8 JavaScript engine.