javascript reduce

javascript reduce method

The javascript reduce method applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.

Directly copied from MDN

reduce executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the array over which iteration is occurring.

The first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.

Summary :-

The reduce method is an acculumator function that provides a simpler way to loop through any javascrpt array from left to right and perform incremental function on all the values.

Some examples to help better understand .reduce

1.Calculate the Sum

var calculateSum = function (a) {
	return a.reduce(function  (i,c) {
		return i+c

console.log(calculateSum([1,2,3,4])); // <= 10

2.Calculate the product of all the elements of the array :-

var calculateProduct = function  (a) {
	return a.reduce(function  (i,c) {
		return i*c;

console.log(calculateProduct([1,2,3,4])); <= 24

3. Calculate the sum of even elements

/* This can be achieved better by using filter Ex.5 */

  if(i%2 === 0){ 
   return a+b;
   return a;
}); //<= 4

4. Flatten an array

var flattenArray = function  (a) {
	return a.reduce(function  (i,c) {
		return i.concat(c);

var b = [[1,2,3],[2,3,4],[4,5,6]];

console.log(flattenArray(b)); //<= [ 1, 2, 3, 2, 3, 4, 4, 5, 6 ]

4. Flatten any array of any level recursively

Here we are passing the second argument as an empty array as that will be the initial value of the accumulator.

var b = [2,[1,2,[3,4]],[2,3,4],[4,5,6]];

var flattenRecursive = function  (arr) {
	return arr.reduce(function  (a,b) {
		if (b instanceof Array) {
			return a.concat(flattenRecursive(b));
			return a.concat(b);

console.log(flattenRecursive(b)); //<= [ 2, 1, 2, 3, 4, 2, 3, 4, 4, 5, 6 ]

5. Using with filter to solve Ex.2

Using filter with reduce makes looping through any array and performing any function much easy.

var filterEvenSum = function  (arr) {
	return arr.filter(function  (a,i) {
		return !(i%2);
	}).reduce(function  (a,b) {
		return a+b;

console.log(filterEvenSum([1,2,3,4])); //<= 4

Main Source :


How to do SVG path animations


Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics that has support for interactivity and animation.

With the imminent dominance of html5 , svg poses a unique advantage for creating unique interactive experiences.Unlike images , svg are responsive in themselves , can be animated , given classes and ids , can be dynamically created and edited.

A primer in SVG is explained at Blog post with the demo at SVG demo

Heres a demo of what we have made

Step 1 : Download Inkscape

Inkscape is an open-source vector graphics editor similar to Adobe Illustrator, Corel Draw, Freehand, or Xara X. What sets Inkscape apart is its use of Scalable Vector Graphics (SVG), an open XML-based W3C standard, as the native format.


You will need Inkscape to create complex paths which will be used for the svg path animations.

screenshot of inkscape

Step 2 : Draw the SVG

Draw the SVG drawing using tools of Inkscape Draw Lines and Bezier Curves.You can edit the curves to suit your needs.This might take some time to make the curves perfect.
Its important to make sure that there is only 1 path throughout the drawing with only one beginning and one end.

Step 3 : Javascript Code for animation

The code works this way , first we give the strokeDasharray property the maximum length of the the path .We also give this length to property strokeDashOffset
Also the path is given a transition of 3s with easing ease-in-out.
Then the property strokeDashOffset is set to 0 which triggers the easing animation.

function  docready () {
	var path = document.querySelector('svg path');
	var length = path.getTotalLength(); = = 'none'; = length + ' ' + length; = length ;

        path.getBoundingClientRect(); = = 'stroke-dashoffset 3s ease-in-out';

	// Below line triggers the Animation = '0';
window.onload = docready;


Step 4 : html file

Copy the svg code generated to any .html file.
To the bottom before the ending body tag , add the above javascript code.
Save it and open the file in your favourite browser.
You can change the stroke-width:4px; to make the line thicker.

There is also a jQuery plugin for it called Lazy Line Painter for making this svg path animations simpler.


The main inspiration for this article :


Simpel | A free single page template for photographers

Simpel is a free responsive html5 template for photographers specially designed for flexibility and ease of use.
This template is a great way to showcase your portfolio and can be adapted for different features and needs.


It has got the following great features :-

  • Single Page Website.
  • Completely optimized for mobile and tablets.
  • 96% PageSpeed.
  • Completely free to use as in speech.
  • Built on top of the awesome framework Bootstrap.
  • Uses css3 animations and transitions for effects.
  • Smooth scrolling to quickly navigate the page.
  • All the images are downloaded from and are free to use for commercial.

Here’s is a full screenshot :

full screenshot of simpel

Subah | A free responsive theme for app showcase

Subah | A free responsive theme for app showcase

Quick Links :



Intro :

There are now more than 1 million apps on android Every app needs a website to showcase the creator or more apps , I am releasing this theme for the app developers.
I hope you like .Subah means morning in Hindi and that is what this theme is : A new beginning.
Did I mention that that it is completely free to use.

Features :-

  • html5 , css3 , jQuery and Modernizr.
  • Completely Responsive.
  • Uses Bootstrap 3.
  • Uses CSS3 transitions as much as possible.
  • Uses flexible nav jquery plugin.
  • Images are downloaded from that is they are free to use.
  • Uses the web best practices
  • PageSpeed – 96% Link

Here are some screenshots :-

jade templating engine

Getting started with jade


Jade is a high performance and feature-rich templating engine heavily influenced by Haml and implemented with JavaScript for node.Jade is a clean, whitespace sensitive syntax for writing html.This a tutorial to get started with jade.

Basic Syntax and command line

Please install node-js for making use of jade.

Run this to install jade globally

npm install -g jade

Fire up your favourite text editor and type this

 Hello World

and save it as hello.jade.

Then from the command line navigate to the directory where you have saved hello.jade and then run jade hello.jade

This will create a new file as hello.html and if you open that in a text editor then it will give :-

<p>Hello World</p>

Be careful not to use spaces and tabs both at the same time :-

Similarly :

this :-

doctype html
    title= pageTitle
      if (foo) {
         bar(1 + 5)
    h1 Jade - node template engine
      if youAreUsingJade
        p You are amazing
        p Get on it!
        Jade is a terse and simple
        templating language with a
        strong focus on performance
        and powerful features.
      p.Hello Hello World

will get converted to

<!DOCTYPE html>
<html lang="en">
		<script type="text/javascript">
			if (foo) {
				bar(1 + 5)
		<h1>Jade - node template engine</h1>
		<div id="container" class="col">
			<p>You are amazing</p>
				Jade is a terse and simple
				templating language with a
				strong focus on performance
				and powerful features.
			<p class="Hello">Hello World</p>

Using jade with express

To understand how to use jade we will have to install node-js and its popular framework express-js.

npm install -g express

Express is bundled with an executable, aptly named express. If you install express globally with npm you’ll have

it available from anywhere on your machine.This tool provides a simple way to get an application skeleton going, but has limited scope, for example it supports only a few template engines, whereas Express itself supports virtually any template engine built for node.

Usage: express [options]


  -h, --help          output usage information
  -V, --version       output the version number
  -s, --sessions      add session support
  -e, --ejs           add ejs engine support (defaults to jade)
  -J, --jshtml        add jshtml engine support (defaults to jade)
  -H, --hogan         add hogan.js engine support
  -c, --css   add stylesheet  support (less|stylus) (defaults to plain css)
  -f, --force         force on non-empty directory

Then run

express jadedemo

This will create all the essential files for a node-js application like app.js and package.json.

After that ,

cd jadedemo && npm install

This is will install all the dependencies required for the application.

Sources and important Links

  1. Jade Official

    [snap url="" alt="jade official"]

  2. Jade Github

    [snap url="" alt="jade github"]

  3. Interactive Tutorial :

    [snap url="" alt="jade github"]

javascript prototype

Understanding javascript prototype

Every object in javascript has got a prototype method which basically adds new methods to the base object which then can be called on instance objects.

Comparing with other languages , constructor functions are classes and the properties of the prototype (i.e. of the object referenced by the constructor function’s prototype property) as shared members, ie members which are the same for each instance. In class-based systems, methods are implemented the same way for each instance, so methods are normally added to the prototype, whereas an object’s fields are instance-specific and therefore added to the object itself during construction.

A simple example

Type this in Chrome Devtools console :

function Animal() {} // This is a first class functional object
Animal.prototype.speak = function() { console.log('OK'); } //Add a prototype function
var cat = new Animal(); //Creates a new Animal
cat.speak(); // Will call that function and print OK

In the above example we first defined the constructor function and then added speak function to it.
We then initialized cat as an Animal and called the that function on it.

Another Example

//Define a functional object to hold Animal
var Animal = function(name) { = name;

//A new getter for that name
Animal.prototype.getName = function() {

//Create a new object of type Animal
var cat = new Animal("Kitty");

//alert(cat.getName()); will use the getter

//This is where we add the speak function to Animal
Animal.prototype.speak = function() {
    alert('Hello, my name is ' + this.getName());

//Call the new method on cat

When you will run the above code in devtools console , you will get an alert saying My name is Kitty.
In the above example , we created the instance object then added a method to the base , and then called the new method on the instance object.
This is how Inheritance works in javascript.

Sources :


Understanding SVG elements using Angular-js

Scalable Vector Graphics are an important part in responsive web-design because instead of using different images for each device you can use svg vectors to define an image and it will automatically scale to the appropriate size.

I have made a small demo for understanding basic svg elements using Angular-js.
Drag the sliders and understand how the svg element as well as the code changes accordingly.


The awesome blog of a Javascript developer.