Posts

Showing posts from June, 2016

Function Chaining in Javascript

What is Method Chaining? Method chaining is a technique that can be used to simplify code in scenarios that involve calling multiple functions on the same object consecutively. Let's write the  Kitten  class with the ability to chain methods. // define the class var Kitten = function () { this . name = 'Garfield' ; this . color = 'brown' ; this . gender = 'male' ; }; Kitten . prototype . setName = function ( name ) { this . name = name ; return this ; }; Kitten . prototype . setColor = function ( color ) { this . color = color ; return this ; }; Kitten . prototype . setGender = function ( gender ) { this . gender = gender ; return this ; }; Kitten . prototype . save = function () { console . log ( 'saving ' + this . name + ', the ' + this . color + ' ' + this . gender + ' kitten...' ); // save to database here...

Variable & Function hoisting in javascript

Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope. Hoisting can be applied to variable declarations and to function declarations. As a result of this, JavaScript functions & variables can be called before they are declared. For example : -  1. variable Hoisting :  x = 8; console.log(x); // prints 8 var x; 2. Function Hositing : -  displayName(); function displayName () { console.log("I am rroxy"); } * Function Hoisting applies to only functions not functions expressions, e.g : - displayName(); // undefined var  displayName = function () { console.log("I am rroxy"); }

Function Currying in Javascript

Currying is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments. Here's an example in JavaScript: function add ( a , b ) { return a + b ; } add ( 3 , 4 ); returns 7 This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function: function add ( a ) { return function ( b ) { return a + b ; } } This is a function that takes one argument, a, and returns a function that takes another argument, b, and that function returns their sum. add ( 3 )( 4 ); var add3 = add ( 3 ); add3 ( 4 ); The first statement returns 7, like the add(3, 4) statement. The second statement defines a new function called add3 that will add 3 to its argument. This is what some people may call a closure. The third statement uses the add3 operation to add 3 to 4, again producing 7 as a result.