WE MOVED!

We moved to new place!!

http://sheberlik.com/

Advertisements

JS: IIFE(Immediately-invoked function expression ) and safe code

Sometimes we need to declare the function and call it immediately. Below code does that, it can also accept the parameter:

var firstname = “John”;

(

function(name){

var greetings = “hello “;

console.log(greetings + name);

}(firstname)

);

So we will see “hello John”. What happens here is that we wrapped the anonymous function inside the (); brackets. This allows to declare the anonymous function. Because JS compiler treats everything inside () as declaration. Then we add function and call it

(funciton() {

}()   // execute it

);

second () actually invokes the function. The rest is easy we just pass the variable that we need. You can see the first example.

My understanding is that this approach is used in many frameworks.  It also possible to put the execute brackets () outside the function wrapper. Both are ok:

(funciton() {

}

)(); // execute it here, both are ok

The beauty of the above code is that it’s safe. By that I mean that this code will run inside it’s own execution context and not global one.

So, variable “greetings” will not clash with variables with same name, but from other places in code.

If, however, we want to overwrite some existing global variable we can do it this way:

File 1, has this code:

var greetings = “Hola”;

File 2, has this code:

var firstname = “John”;

(

function(global, name){

var greetings = “hello “;

global.greetings = “hello”;

console.log(greetings + name);

}(window, firstname)

);

console.log(greetings); // this will output “hello”

// however if we don’t overwrite it, then it will show “Hola”

JS: storing function inside array and calling that function

We can store function inside the array and call it.

Ex.:

var arr = []; // note this creates array in js

var obk = {} // this creates empty ojbect

Ex.2:

var arr = [ “1”,

2,

false,

{ name = “James”,

address = “Mulholland Drive”

},

function(name){

var greeting = “hello “;

console.log(greeting+name);

}

]

Now we have different variables inside our array, we even have another array and function!

To call the stored function:

Note: to call the method use arr[4]()

arr[4](arr[3].name);  // this will get the name from the array under index 3 and pass it to the function

// output will be: hello James

JS function parameters: arguments and Spread

Unlike Java, JS will not throw any errors if the way function is declared and called is different. So there are 2 scenarios when developer passes wrong number of parameters. Either too many or too less

If too many:

Ex: function xyz(x, y,z){

console.log(x);

}

xyz();

// output will be undefined

So, to tackle this potential issue when other developers pass more arguments to a method than it can accept we can use either arguments or spread.

Ex

function abc(a, b,c){

console.log(arguments);

}

// arguments is keyword and will return a,b,c or whatever arguments passed to abc function.

Works a bit similar to this keyword can access it through arguments[n]

Another way is using spread:

Ex.:

function restParam(parameter1, …restArgs){
console.log(restArgs.length); // Logs the number of arguments that do not have a corresponding parameter
console.log(restArgs[2]); // Logs the 3rd argument after the number of arguments that do not have a corresponding parameter
}

restParam(1,2,3,4,5);
// Log would be as follows
// 4
// 4

// 4 is the number of arguments that do not have a corresponding parameter
// 4 is the 4th 3rd argument after the number of arguments that do not have a corresponding parameter

Second way is preferred, because arguments only return array like collection. The keyword is “like”, so some array methods won’t work. (arguments.length and arguments[n] will still work )

Oh, yeah. In the case if there are less parameters passed

If too less:

just assign the functions parameters to a default variable:

fuction zzz(a, b,c){

a= a || “a”;

b=b || 7;

c = c || 10;

}

JavaScript, why are you like this?

JavaScript have some weird quirks. And one of them is how pointer “this” works.

look at the code below:

var c = {
name: "this is c object",
log : function(){
this.name = "updated c object";
var setName = function(newname){
this.name = newname;
}
setName("Updating again! The c object");
console.log(this);
}
}

Look at the line 6, you might think that name has been set to value “Updating again! The c object”, because this is pointing to c object. BUT, if you run the code, you will find out that actually line 6, is creating new Global variable name, and setting it’s value to “Updating again! The c object”. This happens because of how the execution context is created in JavaScript. In JS, the interpreter will hoist all the variables and methods first. Meaning before real execution line 6 is interpreted and variable is set to global variable(sort of being pushed all the way up the code).

The solution would be to store the reference to c object then pass it.

 var c = {
name: "this is c object",
log : function(){
var self = this;
// note some developers use "that" instead of self
self.name = "updated c object";
var setName = function(newname){
self.name = newname;
}
setName("Updating again! The c object");
console.log(self);
}
} 

This way, we will not set the name to be global variable and it will be set to c object. So c.name will return “Updating again! The c object”

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

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