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

How to test your Ajax call using JSP

If you building the web app and want to test your Ajax call by calling the controller here is the snippet you can use.

$(document).ready(function() {
$.ajax({
type: "GET", 
url: "/YourControllerURL"
}).done(function(data) {
console.log(data);
});
});
  1. place the snippet inside the tag inside JSP
  2. in chrome press F12 for developer tools in chrome.
  3. navigate to console tab
  4. in browser navigate to JSP with snippet code.

 

Alternatively, you can view the navigation tab inside the developer tools and see your ajax request and response from controller.

Sweetness of this approach compared to Postman, is that you don’t need to provide all the authorization details.

Note: for testing purpose change your controller to GET method

Note 2: great article to learn about Ajax methods:

https://learn.jquery.com/ajax/jquery-ajax-methods/

Also if you need to pass data to your controller you can use bellow snippet. It returns json, of course your controller must return json too.


var data = {some data you need for your controller ex. id}
$(document).ready(function() {
$.ajax({
type: "GET", 
url: "/YourControllerURL",
contentType: "application/json",
dataType: "json",
data:data
}).done(function (nameOfJsonControllerReturns){ 

console.log(nameOfJsonControllerReturns.data); 

}); 
}); 

Using the Chart.js

I need to use new chart.js to render the pie charts. However, I don’t know how to use it,

these are the steps I followed:

  1. Install node.js from installer then restart
  2. in command prompt: npm install npm -g
  3. add the canvas id to the place where you want to see the chart
    <canvas id="myChart" width="400" height="400"></canvas>
  4. add the script for the chart
    1. <script>
      var ctx = document.getElementById("myChart");
      var myChart = new Chart(ctx, {

      ……………………………..}

new Chart is the constructor for the chart.

 

Action time: Let’s start some project

Dear readers and me, I’ve decided that I should start developing my own application. Only this action can justify my accumulation of knowledge. Therefore, let’s decide on couple things:

  1. Frontend: jQuery, AJAX and JavaScript
  2. Backend: Spring framework

As for app idea, I’ve decided that I will be making clone of project which I’m working on now. But I won’t reuse any materials from it, only the knowledge I’ve acquired. I want my project to be opensource so all the codes will be available on my GitHub account. The link I will put once I got anything to show.

Thank you.

Reflection and Prototyping in JS

Prototyping in java script is nothing but act as an Java Interface. Meaning it’s used to define the methods of the object.

 

 

Reflection in java script is used to observe the content of the object. As for modification we can use method expansion:

ex.:

<p style=”line-height: 18px; font-size: 18px; font-family: times;”>
Click “<i>Load samples</i>” to view and edit more JS samples.<br>

function display(p) {

if (p.hasOwnProperty(‘name’)) {
p.name.lastname = ‘Terry’;
alert(p.name.firstname);
}
}

var person = { combinedname: { fistname: ‘John’ }};
display(person);

</p>

JS: Closure

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain.

The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters

You create a closure by adding a function inside another function.
A Basic Example of Closures in JavaScript:

function showName (firstName, lastName) {
var nameIntro = “Your name is “;
// this inner function has access to the outer function’s variables, including the parameter
function makeFullName () {
return nameIntro + firstName + ” ” + lastName;
}
return makeFullName ();
}
showName (“Michael”, “Jackson”); // Your name is Michael Jackson

Closures are used extensively in Node.js; they are workhorses in Node.js’ asynchronous, non-blocking architecture. Closures are also frequently used in jQuery and just about every piece of JavaScript code you read.

function celebrityID () {
var celebrityID = 999;
// We are returning an object with some inner functions
// All the inner functions have access to the outer function’s variables
return {
getID: function () {
// This inner function will return the UPDATED celebrityID variable
// It will return the current value of celebrityID, even after the changeTheID function changes it
return celebrityID;
},
setID: function (theNewID) {
// This inner function will change the outer function’s variable anytime
celebrityID = theNewID;
}}}

var mjID = celebrityID (); // At this juncture, the celebrityID outer function has returned.
mjID.getID(); // 999
mjID.setID(567); // Changes the outer function’s variable
mjID.getID(); // 567: It returns the updated celebrityId variable

To outcan can use console.log(mjID.getID()); then press F12 in the Chrome to see the console