JavaScript data types, variables, variable scope, literals, hoisting

January 1, 2013

JavaScript has five primitive data types,

  • Undefined 
  • null – a special keyword denoting a null value.
  • Boolean – a logical entity that consists of either a true or false value.
  • Number – a set of numerical digits that represent a number.
  • String – a set of zero or more characters.

Variables

You can use variables as symbolic names for values in application. The names of variables, is called identifiers. Variables can be declared with keyword “var”.

Variable scope

When you declare variables outside of function , its called global variable. When you declare within a function, its called local variable. JavaScript does not have block statement scope.

Hoisting

You can refer to variable declared later without getting exception. This concept is called “Hoisting”, variables in JavaScript are in a sense “hoisted” or lifted to the top of the function.

Constants

You can create read-only, named constant with “const” keyword.  A constant cannot change value through assignment.

Literals

These are fixed values, not variables, that you literally provide in you script.

Array Literals

var coffees = ["French Roast", "Colombian", "Kona"];

Boolean Literals

The boolean type has two literal values “true”, “false”.

Object Literals

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces.

String literals

A string literal is zero or more characters enclosed in double or single quotation marks.

References

https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Values,_variables,_and_literals


JavaScript binding, function apply, function call

December 28, 2012

In JavaScript, binding is always explicit, and can be easily lost, so a method using “this” will not refer to the proper object in all situations,  unless you force it to.

JavaScript provides two options to do explicit binding “apply” and “call”.

Apply

Every JavaScript function is equipped with “apply” method that allows you to call the function with specific binding. I takes two arguments, the binding object and an array of arguments to be passed to the function.

fun.apply(thisArg[, argsArray])

Call

“Call” method is similar to “apply”, but it takes the arguments themselves not an array.

fun.call(thisArg[, arg1[, arg2[, ...]]])

References

http://www.alistapart.com/articles/getoutbindingsituations

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call

http://stackoverflow.com/questions/962033/what-underlies-this-javascript-idiom-var-self-this


JavaScript event delegation

December 27, 2012

JavaScript event delegation is a simple technique by which you add a single event handler to a parent element in order to avoid having to add event handlers to multiple child elements.

Event capturing

Netscape defined an approach called event capturing, where events occur on the highest object in the DOM tree and then work down to the deepest element affected by the event.

Event bubbling

IE defined event bubbling. The deepest element affected by the event should receive the event first , then its parent, etc., until the document object finally receives the event.

W3C DOM level 2 events specification defines both event bubbling and capturing. First the document receives the event, then the capturing phase commences to the most specific element affected by the event. Once the event is handled by the element, it bubbles back up to the document.

Advantages

  • Less event handlers to setup and reside in memory.
  • No need to re-attach handlers after a DOM update.

http://www.nczonline.net/blog/2009/06/30/event-delegation-in-javascript/

http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/


JavaScript private public privileged access

December 26, 2012

Public

The members of an object are all public members. There are two ways for putting members in a new object.

In Constructor

function Container(param) {
    this.member = param;
}

In the prototype

This technique is used to add public methods.

Container.prototype.stamp = function (string) {
    return this.member + string;
}

Private
Private members are made by the constructor. Ordinary vars and parameters of the constructor become the private members.

function Container(param) {
    this.member = param;
    var secret = 3;
    var that = this;
}

Privileged

A privileged method is able to access private methods, variables and is itself accessible to the public method and the outside.  Privileged methods are assigned with “this” within the constructor.

function Container(param) {
    this.member = param;

    this.service = function () {
        return this.member;
    };
}

 

http://javascript.crockford.com/private.html

http://phrogz.net/JS/classes/OOPinJS.html

https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Inheritance_and_the_prototype_chain

https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript


JavaScript function declaration, function expression, Function constructor, Anonymous function

December 25, 2012

Function declaration –

function name([param[, param[, ... param]]]) {
   statements
}
example -
function sum(a, b)
{
    return a + b;
}

name – The function name

param – The name of the argument to be passed to the function. A function can have up to 255 arguments.

statements – The body of the function

Function expression and Anonymous function –

function [name]([param] [, param] [..., param]) {
   statements
}
example -
var sum = function(a, b) { return a + b; }

The name can be omitted in which case it becomes anonymous function.
Anonymous functions can help make code more concise when declaring a function that will only be used in one place.

Function constructor –

Function objects can be created with new operator

new Function (arg1, arg2, ... argN, functionBody)

example - 
var sum = new Function('a','b', 'return a + b;');

arg1, arg2, … argN – zero or more names to be used by the function as argument names

functionBody – A string containing JavaScript statements forming the function body.

References
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope

http://helephant.com/2008/08/23/javascript-anonymous-functions/

http://stackoverflow.com/questions/1140089/how-does-an-anonymous-function-in-javascript-work

 


Object Oriented Programming

December 19, 2012

Object

Object is an instance of a class.  All objects have a state and behavior.

Class

Class is the blueprint from which individual objects are created

Inheritance

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses.

Interface

Methods form the object’s interface with the outside world. An interface is a group of related methods with empty bodies.  Interface separates implementation and defines the structure. It is useful when the implementation changes frequently.  Interface forms a contract between the class and the outside world.

Abstract Class

Abstract classes cannot be instantiated.  It can only be used as a super class for other classes that extend the abstract class.  Abstract classes are declared with keyword abstract.  Abstract class methods can have implementations. Abstract class’s methods can’t have implementation only when declared abstract.

Encapsulation

Encapsulation is inclusion within a program object of all the resources needed for the object to function.  It allows class to change its internal implementation without hurting the overall functioning of the system.

Polymorphism

Polymorphism is the ability to request that the same operations be performed by a wide range of different types of things.

Method overloading

Ability to define several methods all with the same name

Method overridding

Subclass overrides a specific implementation of a method that is already provided by one of its super classes.

References

http://docs.oracle.com/javase/tutorial/java/concepts/object.html

http://www.codeproject.com/Articles/22769/Introduction-to-Object-Oriented-Programming-Concep#OOP


JavaScript arguments, prototype, constructor, inheritance

December 16, 2012

Arguments

In every JavaScript function a private variable argument is automatically created, holding array of the arguments passed to the function.

Prototype

Every object has a special property, prototype. This property allows you to add properties/methods to all objects created from that object constructor. The prototype object loads before the object constructor does anything. Therefore by using prototype we can add properties, methods to both native objects and user-defined objects.

Constructor

Every instance of an object has a constructor property. It returns the Function object that created that instance of the object.

Inheritance

The prototype property is an object with no initial properties/methods. When we add properties/methods to this object, we automatically add them to all instances of the object. However, instead of adding properties/methods to the prototype object, we could replace the prototype object with an object that already has the properties/methods we want.

References

http://www.sitepoint.com/oriented-programming-2/

https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript


Java Collections

December 16, 2012

A collection is a object that groups multiple elements into a single unit.

List of core collection Java interfaces.

  • Collection – This interface is the least common denominator that all collections implement and is used to pass collections around and manipulate them where maximum generality is desired.
  • Set – A collection that cannot contain duplicate elements
  • List – A ordered collection that can contain duplicate elements. Elements can be accessed by their integer index.
  • Queue – A collection which orders elements in first-in, first-out manner.
  • Map – An object which maps keys to values. There cannot be duplicate keys.
  • SortedSet – A set that maintains its elements in ascending order.
  • SortedMap – A map that maintains its mappings in ascending order.

Ways to traverse a collection.

  • for-each
for (Object o : collection)
    System.out.println(o);
  • Iterators – It enables to traverse a collection and to remove elements selectively. Iterator.remove is the only safe way to modify a collection during iteration
static void filter(Collection<?> c) {
    for (Iterator<?> it = c.iterator(); it.hasNext(); )
        if (!cond(it.next()))
            it.remove();
}

toArray method – translates collection to array.

Object[] a = c.toArray();
String[] a = c.toArray(new String[0]);

Set Implementations.

  • HashSet – Stores elements in hash table. Good performance, but makes no guarantee about order.
  • TreeSet – Stores elements in red-black tree, orders elements by values, slower than HashSet. SortedSet implementation.
  • LinkedHashSet – Implements a hash table with a linked list running through it, orders elements based on the order in which they were inserted.

List Implementations.

  • ArrayList – provides constant time positional access and is fast
  • LinkedList – offers better performance under certain circumstances. If you add elements to beginning of list or iterate over the list to delete elements.

Map Implementations.

  • HashMap – Provides maximum speed, but not ordered.
  • TreeMap – Ordered by the keys. SortedMap implementation.
  • LinkedHashMap – Provides intermediate performance of the above two implementation. Ordered by insertion.

References

http://docs.oracle.com/javase/tutorial/collections/interfaces/index.html


REST Principles

December 13, 2012

REST stands for Representational State Transfer

5 key principles of REST are –

  • Give everything a ID

Examples
http://example.com/orders/2007/11
http://example.com/products?color=green

  • Link things together

Links help to refer to identifiable things

  • Use standard methods

GET- To retrieve a representation. Its idempotent, meaning that has no additional effect if it is called more than once with the same input parameters
PUT – update this resource with this data, or create it at this URI if it’s not there already. Its idempotent.
DELETE – delete a resource. Its idempotent.
POST – create a new resource. Its not idempotent.

  • Resources with multiple representations

Provide multiple representations of resources for different needs.

  • Communicate statelessly

A server should not have to retain some sort of communication state for any of the clients it communicates with beyond a single request. The most obvious reason for this is scalability — the number of clients interacting would seriously impact the server’s footprint if it had to keep client state.

https://www.ibm.com/developerworks/webservices/library/ws-restful/
http://tomayko.com/writings/rest-to-my-wife
http://www.infoq.com/articles/rest-introduction


Javascript Object oriented programming

August 22, 2012
  • JavaScript is a prototype-based language which contains no class statement. Instead JavaScript uses functions as classes. Defining a class is as easy as defining a function.
  • An object constructor/object constructor function is a function that’s used to define a new object. In this function, we declare the initial properties/methods of the new object, and usually assign them a pre-defined value.
  • To create an instance of an object, we use the keyword “new”, followed by an object constructor. We can either use JavaScript’s built-in constructors to create a native object, or we can build our own constructors to create a user-defined object.
  • Every object method has a variable – this – which refers to the current instance of that object from which the method is called.

Example

     function Computer(name) {
          this.name=name;
          this.getName=function() {
             return this.name;
          }
     }

     var computer1 = new Computer("Desktop-1");
     alert(computer1.getName());//alerts Desktop-1
     var computer2 = new Computer("Desktop-2");
     alert(computer2.getName());//alerts Desktop-2

References

http://www.sitepoint.com/oriented-programming-1/

https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript