Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Arrow functions in JavaScript

Posted in ECMAScript, Javascript

Arrow functions are newly added type of functions in ES6(ECMAScript 6). They are just a compressed way of writing normal functions.

Arrow functions are also called as ‘Fat Arrow functions’.

function add(x, y) {
  return (x+y);
}

var result = add(6,5); // will output 11

This is the normal JavaScript function. Let’s see how above code is written using arrow functions.

var add = (x, y) => {
    return x+y;
};

var result = add(6,5); // will output 11

Look at the above code “function” keyword is replaced by fat arrow. Here is another shortest form of arrow function if we have one line of code inside function body, we can skip those curly braces and ‘return’ keyword while returning values from the function.

  var add = (x, y) => x+y;

If we have multiple lines inside function body then use of curly brace is mandatory. Let’s try using arrow functions in constructor functions.

function Car() {
    this.name = 'BMW';
    this.speed = 50;

    this.increaseSpeed= function() {
       this.speed+= 10;
    }
}

Now, create an object for the Car function.

var mycar= new Car();

mycar.increaseSpeed(); 
console.log(mycar.speed); // will output 60

But consider a case where we want to increase the car speed after 5 seconds. We will use setTimeout function here.

function Car() {
    this.name = 'BMW';
    this.speed = 50;

    this.increaseSpeed= function() {
      setTimeout(function() {
         this.speed+= 10;
      }, 3000);  
    }
}

var mycar= new Car();
mycar.increaseSpeed(); 
console.log(mycar.speed); // will output 50

In this case, after calling increaseSpeed function will not increase the car speed because we are calling a member variable ‘speed’ inside setTimeout function and this setTimeout function has it’s own scope. So the constructor function car’s scope is lost and ‘this’ variable inside setTimeout function has no longer access to the car constructor.

In order to access member variables using ‘this’ keyword inside setTimeout scope use fat arrow functions.

Look at the Car constructor function using arrow function.

function Car() {
    this.name = 'BMW';
    this.speed = 50;

    this.increaseSpeed= function() {
      setTimeout(() => {
         this.speed+= 10;
      }, 3000);
    }
}

var mycar= new Car();
mycar.increaseSpeed(); 
console.log(mycar.speed); // will output 60

We have replaced the setTimeout function syntax to fat arrow function. Fat arrow syntax preserve ‘this’ context. So no need to save the context in any temporary variable like that or self and use that temporary variable inside setTimeout function.

To summarize shorter syntax and flexibility of this keyword context these are the main advantage of using arrow functions

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Creating a simple grunt task

Posted in Javascript

Grunt is a JavaScript task runner used to automate the common tasks such as JS/CSS file minimization, concatenation of multiple JS/CSS files, Sass compilation, JS linting, code formatting etc.

To get started with grunt you need to install node JS latest version from node JS website.

https://nodejs.org/

Create Node project

From node.js command prompt, go to the project directory.
grunt-1

Type: “npm init”, then: “enter”
grunt-2
follow steps, enter only a name for the site, no need to change other default values. “npm init” command creates a package.json file. Refer the screenshot below.
grunt-3

Install grunt
Use the npm command below to install grunt specific to your project.
grunt-4
–save-dev command adds the dev dependency in the package.json file.
package.json file will look like this.
grunt-5

Create Gruntfile.js in the project root directory. We will use this file to create and configure grunt tasks. Add the below code in the Gruntfile.js.
grunt-12

It’s time to create a grunt task. Create a simple grunt task named logTask using grunt.registerTask function.

  grunt.registerTask('logTask', function() {
    console.log('Inside Log Task');
  });

Your gruntfile will look like this.
grunt-6

Now call the logTask using the command below. “Inside Log Task” text will get printed in the console.

     grunt  logTask

grunt-7

You can create multiple grunt task in the same Gruntfile.
grunt-8

To call the formatTask use the command below.

    grunt formatTask

grunt-9

You can run the above tasks simultaneously by calling both task into the new task.
grunt-10

grunt-11

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Custom Filter in Angular JS

Posted in Angular JS

To register a filter you need to call the function angular.module().filter(). The first argument is the name of the filter. The second argument is the filter
factory function. If your filter has dependencies, you can list those as arguments in this function.

Syntax:

custom-filter-angularjs

The factory function returns an anonymous function i.e function with no name or so called as self executing function. This anonymous function accepts one argument which is input to the filter. Second argument is optional it depends on filter functionality. If you want to filter objects from an array then the second parameter can be an array.

Example:

The example metioned below is for a custom filter which reverse the input string.

   var myApp = angular.module("myApp", []);
   myApp.filter("reverse", function() {
    return function(input) {
        if (input !== undefined) {
            return split("").reverse().join("");
        }
    };
   });

   <div>{{ firstname | reverse  }}</div>

The above filter first checks for the input is undefined or not otherwise the filter throws an error on page load. It returns an revers of firstname using reverse and join javascript functions.

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Built in Angular JS Directives

Posted in Angular JS, Javascript

HTML 5 provides flexibility to create custom tags and attributes. Angular use the same HTML 5 concept to provide additional functionality using these custom tags and attributes. Angular JS has built in directives listed as below.

  • ng-app: Declares the root element of an Angular JS application, under which directives can be used to declare bindings and define behavior.
  • ng-bind: Sets the text of a DOM element to the value of an expression. For example, <span ng-bind=”name”></span> will display the value of ‘name’ inside the span element. Any changes to the variable ‘name’ in the application’s scope are reflected instantly in the DOM.
  • ng-model: Establishes a two-way data binding between the view and the scope. Mostly used with form controls such as Textbox, select dropdown, checkbox, radio button etc.
  • ng-class: Allows class attributes to be dynamically loaded.

     <div ng-class="{'classname': expression}"> ... >/div> 
  • ng-controller: Specifies a JavaScript controller that evaluates HTML expressions.
  • ng-show & ng-hide: Conditionally show or hide an element, depending on the value of a boolean expression. Show and hide is achieved by setting the CSS display style.
  • ng-switch: Conditionally instantiate one template from a set of choices, depending on the value of a selection expression.
  • ng-view: The base directive responsible for handling routes that resolve JSON before rendering templates driven by specified controllers.
  • ng-if: Basic if statement directive that allow to show the following element if the conditions are true. When the condition is false, the element is removed from the DOM. When true, a clone of the compiled element is re-inserted.
  • ng-disabled: Add HTML 5 “disabled” attribute based on the condition to disable any HTML element.
  • ng-options: The ng-options directive fills a <select> element with <options>.

Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

$rootScope in Angular JS

Posted in Angular JS

rootscope
$rootScope refers to an object which is accessible from everywhere of the application. You can think $rootScope as global variable which can be accessible in all controllers, services, directives. The $rootScope object has a function called $new() that’s used to create child scopes.

Angular JS finds ng-app and therefore creates a $rootScope object. Next, while traversing the DOM, Angular JS encounters another ng-controller directive which points to “myController”. Now, it creates another child scope using $rootScope.$new() called $scope.

Injecting rootScope in a controller:
rootscope