More about JavaScript closures

From my understanding closures is extremely important concept in JavaScript. Let’s learn it in details:

Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions ‘remember’ the environment in which they were created.

Lexical Scooping

Lexical scooping is a type of closure.

function init() {
var name = “Mozilla”; // name is a local variable created by init
function displayName() { // displayName() is the inner function, a closure
alert (name); // displayName() uses variable declared in the parent function
}
displayName();
}
init();

Here you can notice that init() has function inside. Then when init is called, that function is called too.

Git: how to use cherry pick using smartgit

If you have have multiple git branches and you have pushed your code to branch x, but you also want it to be available on other branch too ex.: branch Y, then perform following steps:

  1. Checkout the branch Y, the place where you want to push your code
  2. Then from toolbar above, Branch->Cherry Pick
  3. Click Branches, and un-select the Head. Then select the branch X. Choose the commit you want to add to branch Y.
  4. Select and press Cherry pick and commit
  5. then press Push
  6. Done

Now branch Y has commit from branch X.

10 JavaScript concepts

original link: http://www.javaworld.com/article/3196070/application-development/10-javascript-concepts-nodejs-programmers-must-master.html

1. Immediately invoked function expressions

(function(){
                        // all your code here
                        // ...
            })();

this will immediatlly execute the code

2. Closures

A closure in JavaScript is an inner function that has access to its outer function’s scope, even after the outer function has returned control. A closure makes the variables of the inner function private

var count = (function () {
            var _counter = 0;
            return function () {return _counter += 1;}
})();
count();
count();
count();
// the counter is now 3

3. Prototypes

Every JavaScript function has a prototype property that is used to attach properties and methods. This property is not enumerable. It allows the developer to attach methods or member functions to its objects. JavaScript supports inheritance only through the prototype property. In case of an inherited object, the prototype property points to the object’s parent. A common approach to attach methods to a function is to use prototypes as shown below:

function Rectangle(x, y) {
            this._length = x;
            this._breadth = y;
}

Rectangle.prototype.getDimensions = function () {
            return { length : this._length, breadth : this._breadth };
};

Rectangle.prototype.setDimensions = function (len, bred) {
            this._length = len;
            this._breadth = bred;
};

4. Private properties, using closures

JavaScript lets you define private properties by special technique. By default js don’t provide any private property. We use _ on the variable name as convention to let everyone know that this is private variable.

Defining private properties using closures will help you solve this problem. The member functions that need access to private properties should be defined on the object itself. You can make private properties using closures as shown below:

function Rectangle(_length, _breadth) {
            this.getDimensions = function () {
            return { length : _length, breadth : _breadth };
            };

            this.setDimension = function (len,bred) {
            _length = len;
            _breadth = bred
            };
}

5. The Module pattern

The Module pattern is the most frequently used design pattern in JavaScript for achieving loosely coupled, well-structured code. It allows you to create public and private access levels. One way to achieve a Module pattern is shown below:

var Direction = (function() {
  var _direction = 'forward'

  var changeDirection = function(d) {
            _direction = d;
  }

  return {
            setDirection: function(d) {
            changeDirection(d);
            console.log(_direction);
            }
  };

})();

Direction.setDirection('backward');   // Outputs: 'backward'
console.log(Direction._direction);

6. Hoisting

JavaScript moves variables and function declarations to the top of their scope before code execution. This is called hoisting. Regardless of where you place the declaration of functions and variables in your code, they are moved to the top of their scope by the interpreter.

The priority is given below from higher to lower:

  • Variable assignment
  • Function declaration
  • Variable declarations

x = 5; // Assign 5 to x

elem = document.getElementById(“demo”); // Find an element
elem.innerHTML = x;                     // Display x in the element

var x; // Declare x

Declare Your Variables At the Top !

7. Currying

A technique using partial evaluation. Currying refers to the process of transforming a function with multiple arity into the same function with less arity. The curried effect is achieved by binding some of the arguments to the first function invoke, so that those values are fixed for the next invocation.

var myFirstCurry = function(word) {
  return function(user) {
            return [word , ", " , user].join("");
  };
};

var HelloUser = myFirstCurry("Hello");
HelloUser("Rahul"); // Output: "Hello, Rahul"

The original curried function can be called directly by passing each of the parameters in a separate set of parentheses one after the other as shown below:

myFirstCurry("Hey, wassup!")("Rahul"); // Output: "Hey, wassup!, Rahul"

8. The apply, call, and bind methods

It’s imperative for any JavaScript developer to understand the difference between the call, apply, and bind methods.

Of the three, call is the easiest. It’s the same as invoking a function while specifying its context. Here’s an example:

var user = {
     name: "Rahul Mhatre",
     whatIsYourName: function() {
     console.log(this.name);
     }
};

user.whatIsYourName(); // Output: "Rahul Mhatre",
var user2 = {
     name: "Neha Sampat"
};

user.whatIsYourName.call(user2); // Output: "Neha Sampat"

apply is nearly the same as call. The only difference is that you pass arguments as an array and not separately. Arrays are easier to manipulate in JavaScript, opening a larger number of possibilities for working with functions. Here is an example using apply and call:

var user = {
     greet: "Hello!",
     greetUser: function(userName) {
     console.log(this.greet + " " + userName);
     }
};

var greet1 = {
     greet: "Hola"
};

user.greetUser.call(greet1,"Rahul") // Output: "Hola Rahul"

user.greetUser.apply(greet1,["Rahul"]) // Output: "Hola Rahul"

The bind method allows you to pass arguments to a function without invoking it. A new function is returned with arguments bounded preceding any further arguments. Here is an example:

           var user = {
                greet: "Hello!",
                greetUser: function(userName) {
                console.log(this.greet + " " + userName);
                }
           };

           var greetHola = user.greetUser.bind({greet: "Hola"});
           var greetBonjour = user.greetUser.bind({greet: "Bonjour"});

           greetHola("Rahul") // Output: "Hola Rahul"
           greetBonjour("Rahul") // Output: "Bonjour Rahul"

9. Memoization

Memoization is an optimization technique that speeds up function execution by storing results of expensive operations and returning the cached results when the same set of inputs occur again. JavaScript objects behave like associative arrays, making it easy to implement memoization in JavaScript. For example, we can convert a recursive factorial function into a memoized factorial function as shown below:

function memoizeFunction(func) {
  var cache = {};
  return function() {
            var key = arguments[0];
            if(cache[key]) {
            return cache[key];
            }
            else {
            var val = func.apply(this, arguments);
            cache[key] = val;
            return val;
            }
  };
}

var fibonacci = memoizeFunction(function(n) {
  return (n === 0 || n === 1) ? n : fibonacci(n - 1) + fibonacci(n - 2);
});

10. Method overloading

Method overloading allows multiple methods to have the same name but different arguments. The compiler or interpreter determines which function to call based on the number of arguments passed. Method overloading is not directly supported in JavaScript. But you can achieve something very much like it as shown below:

function overloadMethod(object, name, fn){

            if(!object._overload){
            object._overload = {};
            }

            if(!object._overload[name]){
            object._overload[name] = {};
            }

            if(!object._overload[name][fn.length]){
            object._overload[name][fn.length] = fn;
            }

              object[name] = function() {
                        if(this._overload[name][arguments.length])
                        return this._overload[name][arguments.length].apply(this, arguments);
              };
}

function Students(){
  overloadMethod(this, "find", function(){
            // Find a student by name
  });

  overloadMethod(this, "find", function(first, last){
            // Find a student by first and last name
  });

}

var students = new Students();
students.find(); // Finds all
students.find("Rahul"); // Finds students by name
students.find("Rahul", "Mhatre"); // Finds users by first and last name

Let’s learn JS! Reading the “JS Good Parts book”

I’ve decided to start learning Javascript because I want understand how it works.

Let’s start with Functions:

Function invocation:

In addition to the declared parameters, every function receives two additional parameters: this and arguments. The this parameter is very important in object oriented programming, and its value is determined by the invocation pattern. There are four patterns of invocation in JavaScript: the method invocation pattern, the function invocation pattern, the constructor invocation pattern, and the apply invocation pattern. The patterns differ in how the bonus parameter this is initialized.

Note: if too many or too little parameters passed to function they will be ignored or set to undefined. There is no type checking. Also this will not throw any runtime errors.

1.Method invocation pattern

// Create myObject. It has a value and an increment
// method. The increment method takes an optional
// parameter. If the argument is not a number, then 1
// is used as the default.
var myObject = {
value: 0,
increment: function (inc) {
this.value += typeof inc === ‘number’ ? inc : 1;
}
};
myObject.increment( );
document.writeln(myObject.value); // 1
myObject.increment(2);
document.writeln(myObject.value); // 3

2. Function invocation pattern

 

3. Constructor invocation pattern

 

4. Apply invocation pattern

 

2 ways of binding data to JSP

There are 2 ways of binding data to the JSP.

  1. Using JSTL. JSTL can help to retrieve the data from the server and populate it in the JSP. But the issue is that we can’t dynamically add the html elements inside the JSP.
  2. Using Handlebars. We can get the data from ajax calls inside the JS, then add it to handlebar then append the handlebar to JSP. This way allows us to add multiple elements and make the page dynamic. Remember to compile the handlebar inside the JS

 

tags: jsp, javascript, jsp data binding

JS: function inside () followed by (). ~ inside the if statment

if the function is inside the () and followed by () ex:

( fucntion(){

})

()

This means that we declared the function and run it immediately

~ inside if statement means “not”, and works similar to !. ex:
if(~tagsArray.indexOf(item)) {

something;
}

means if no items inside the array do something

JS lesson 2: CSS pseudo class

We can use CSS pseudo class to select items we need.

<select>
<optgroup>
<option selected>1</option>
<option>2</option>
<option>3</option>
</optgroup>
</select>
select option:selected === select > optgroup > option:selected

select option:myproperty  // this is wrong

Javascrint and Jquery way of finding elements
select option:first-child === $(select).find(option).first();
select option:last-child === $(select).find(option).first();