Wednesday, June 5, 2013

JavaScript Learning# 7 - Static variables and methods

Static variables and methods

A function is an object. That provides us with a nifty way to create static variables or, in other words, the variables which persist along multiple calls.
For example, we want a variable which counts function calls.

Static variables

There are languages which allow to put a static keyword before a variable, and then such variable is not cleared in next calls.
Example of a static variable in Java language:
1static int count = 0;void f() { 
2
3 count++;
5}
6 
7new f(); new f(); new f(); // 1 2 3
In JavaScript, there is no term or keyword static, but we can put such data directly into function object (like in any other object).
1function f() {
2  f.count = ++f.count || 1 // f.count is undefined at first
3 
4  alert("Call No " + f.count)
5}
6 
7f(); // Call No 1
8f(); // Call No 2
Of course, a global variable can keep the counter, but static variables lead to a better architecture.
We could make the code more universal by replacing f with arguments.callee.
1function f() {
2  arguments.callee.count = ++arguments.callee.count || 1
3 
4  alert("Called " + arguments.callee.count + " times")
5}
Now you can safely rename the function if needed Smile

Static methods

Static methods, just like variables, are attached to functions. They are used mostly for objects:
01function Animal(name) {
02  arguments.callee.count = ++arguments.callee.count || 1
03 
04  this.name = name
05}
06 
07Animal.showCount = function() {
08  alert( Animal.count )
09}
10 
11var mouse = new Animal("Mouse")
12var elephant = new Animal("elephant")
13 
14Animal.showCount()  // 2




Tuesday, June 4, 2013

JavaScript Learning # 6 - Local and global variables

The "scope" of a variable refers to the variable's visibility within a program. Variables which are accessible only to a restricted portion of a program are said to have "local scope." Variables that are accessible fromanywhere in the program, however, are said to have "global scope."
In JavaScript, variables fall into two major categories: global and local. Global variables are accessible from anywhere in the program and retain their values until the document is unloaded. Local variables, on the other hand, are created during function calls for temporary use and are accessible only within the functions that create them.
In this article I will demonstrate the use of global and local variables in JavaScript, explain the differences between them, and demonstrate why both types are useful. It is assumed that you are familiar with other aspects of JavaScript programming and that you know what a variable is.

global variables

The following JavaScript example creates two global variables (year and month), assigns values to them, and then prints their values:

year = 1997; function make_month_variable () { month = 2; } make_month_variable (); document . write ("year=" + year + " and month=" + month);
If you are familiar with traditional structured programming languages, such as Pascal or C, you might see some strange things in this code:
  1. Variables are not formally declared before values are assigned to them.
  2. Although the variable month is created inside a function, it is not actually used until after the function returns.
Global variables can be created anywhere in JavaScript code, simply by assigning initial values to them.* Once created, global variables can be accessed from any part of the script and retain their values until the document is unloaded.
In JavaScript, newly created variables are assumed to be global, regardless of where they are created, unless explicit measures are taken to make them local. In the example shown above, the variable month is created when the function is called, not defined. After the function returns, however, the month variable retains its definition. (Otherwise, the write statement would result in a JavaScript error.)
In summary, you should use global variables to store values that
  • must be maintained throughout the life of the document (i.e., until the document is unloaded) or
  • need to be accessed from many points in the program.
If your functions are using global variables that don't satisfy either of these two requirements, then you should consider rewriting them so that they use local variables instead.

local variables

Local variables store temporary variables during a short, well-defined block of code, such as a function, and are accessible only within the block where they are defined. Local variables can only be created in functions; this is done by preceding the first instance of the variable's name with the keyword var. In the example shown below, a local variable named x is created and initialized with the value 5.
function foo ()
{
 var x;
 x = 5;
 .
 .
 .
}
 ...or... 
function foo ()
{
 var x = 5;
 .
 .
 .
}
By the way, function parameter variables are considered local variables. (There are a few exceptions to this rule, but mentioning them here will only make things more complicated. :-)
Local variables are accessible only in the functions where they are created. When functions exit, all of their local variables are automatically destroyed.

global and local variables with the same names

A potential ambiguity arises when two distinct variables -- one global and one local -- have the same names. The JavaScript interpreter resolves this ambiguity by giving priority to local variables whenever possible. Thus, it is possible for global variables to become masked, or hidden from the interpreter's view, when local variables exist by the same names. Although masked global variables retain their values, they are not (easily) accessible until the local variables masking them fall out of scope.
Local variables fall out of scope in two ways:
  1. A function exits and its local variables are automatically destroyed.
  2. A function calls another function, thus suspending the first function and all of its local variables.
In the first case, the variables fall out of scope simply because they cease to exist. In the second case, the local variables are only temporarily out of scope and will become visible again when the called function returns.
Each time a function is entered, a separate "variable space" is created for the function's local variables. Thus, even when a function repeatedly calls itself, the local variable space created for the outer function call is unrelated to the variable space created for the inner function call.

an example

The following example is given to illustrate the behavior of global and local variables. This example will also demonstrate how local variables can mask global variables. Consider the JavaScript code shown below:
function function_1 () { var x = 5; document . write ("<br>Inside function_1, x=" + x); function_2 (); document . write ("<br>Inside function_1, x=" + x); } function function_2 () { document . write ("<br>Inside function_2, x=" + x); } x = 1; document . write ("<br>Outside, x=" + x); function_1 (); document . write ("<br>Outside, x=" + x);
When executed, the values of two distinct variables, both named x, will be printed. The following table describes the process:
explanationillustrationprogram output
A global variable named x is created and initialized with the value 1. This value is output to the document.Outside, x=1
function_1 is called. As it executes, a local variable named x is created and set to 5. Because this local variable has the same name as the global variable, the global variable is masked and the function's first write statement outputs the value 5, not 1.Inside function_1, x=5
function_1 calls function_2. Because function_2 cannot see function_1's variables, the reference to x in function_2 is interpreted as a reference to the global variable. Thus, a value of 1 is written to the document.Inside function_2, x=1
When function_2 returns, however, function_1 continues where it left off, and the local variable comes out of hiding. Thus, a value of 5 is again written to the document.Inside function_1, x=5
Finally, when function_1 finishes, the local variable x is destroyed and the global variable is the only one left. Thus, a value of 1 is written to the document.Outside, x=1

Difference between using var and not using var in JavaScript ?

If you're in the global scope then there's no difference!!.

If you're in a function then "var" will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):

// These are both globals
var foo = 1;
bar = 2;

function()
{
    var foo = 1; // Local
    bar = 2;     // Global

    // Execute an anonymous function
    (function()
    {
        var wibble = 1; // Local
        foo = 2; // Inherits from scope above (creating a closure)
        moo = 3; // Global
    }())
}


conclusion

So what's the big deal about local and global variables? Why not make them all global and be done with it?

Decades ago, when system memory was expensive, local variables were used to conserve memory. Variables were created on demand, used for a while, and then destroyed so that the memory used to store their values could be recycled for other variables. Although this once was a pretty good reason for using local variables, it is hardly worth mentioning in a JavaScript environment. There are better reasons than this.

Experienced programmers support a programming philosophy called "the principle of least privileges." This philosophy says that if the accessibility of a program resource, such as a function or variable, is restricted to just those portions of the program where such accessibility is required, then the programmer is less likely to introduce errors into the code without noticing them quickly.
Another good reason for using local variables is that less effort is required to keep track of variable names. Since each function call results in the creation of a new variable name space, different functions can use the same variable names without treading on each other's variables.
For these reasons, it is considered good programming practice to use local variables whenever possible. In JavaScript, this means your functions should use local variables to store temporary values that will not be needed after the function returns -- loop variables, for example. Adopting a habit of using local variables whenever possible will help you avoid subtle JavaScript coding errors that might not be noticed until after your web page is published.

source: http://sharkysoft.com/tutorials/jsa/content/031.html

Difference between equals() and == in Java?


What’s the difference between equals() and ==?

Before discussing the difference between “==” and the equals() method, it’s important to understand that an object has both a location in memory and a specific state depending on the values that are inside the object.

The “==” operator

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location. A very simple example will help clarify this:
String obj1 = new String("xyz");

String obj2 = new String("xyz");

if(obj1 == obj2)
   System.out.println("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");
    

Take a guess at what the code above will output. Did you guess that it will outputobj1==obj2 is TRUE? Well, if you did, then you are actually wrong. Even though the strings have the same exact characters (“xyz”), The code above will actually output:
 obj1==obj2 is FALSE

The “==” operator compares the objects’ location(s) in memory

Are you confused? Well, let us explain further: as we mentioned earlier, the “==” operator is actually checking to see if the string objects (obj1 and obj2) refer to the exact same memory location. In other words, if both obj1 and obj2 are just different names for the same object then the “==” operator will return true when comparing the 2 objects. Another example will help clarify this:
String obj1 = new String("xyz");

// now obj2 and obj1 reference the same place in memory
String obj2 = obj1;

if(obj1 == obj2)
   System.out.printlln("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

Note in the code above that obj2 and obj1 both reference the same place in memory because of this line: “String obj2 = obj1;”. And because the “==” compares the memory reference for each object, it will return true. And, the output of the code above will be:
obj1==obj2 is TRUE

The equals() method

Now that we’ve gone over the “==” operator, let’s discuss the equals() method and how that compares to the “==” operator. The equals method is defined in the Object class, from which every class is either a direct or indirect descendant. By default, the equals() method actually behaves the same as the “==” operator – meaning it checks to see if both objects reference the same place in memory. But, the equals method is actually meant to compare the contents of 2 objects, and not their location in memory.
so, how is that behavior actually accomplished? Simple – the equals class is overridden to get the desired functionality whereby the object contents are compared instead of the object locations. This is the Java best practice for overriding the equals method – you should compare the values inside the object to determine equality. What value you compare is pretty much up to you. This is important to understand – so we will repeat it: by default equals() will behave the same as the “==” operator and compare object locations. But, when overriding the equals() method, you should compare the values of the object instead.

An example of the equals() method being overriden
The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal. Here is an example that will help clarify this:
String obj1 = new String("xyz");

String obj2 = new String("xyz");

if(obj1.equals(obj2))
   System.out.printlln("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");


This code will output the following:
obj1==obj2 is TRUE
As we discussed, Java’s String class overrides the equals() method to compare the characters in a string. This means that the comparison between the 2 String objects returns true since they both hold the string “xyz”. It should now be clear what the difference is between the equals() method and the “==” operator.

Other example is:
StringBuffer s1 = new StringBuffer("kondal");
StringBuffer s2 = new StringBuffer("kondal");
System.out.println(s3.equals(s4));  //false

Above comparison results 'false' because of StringBuffer has not overridden equals() method as like String class.So, equals() comparison on StringBuffer same as '==' comparison, since it looks for Object 'equals()' method.

String s3 = "kondal";
Now, System.out.println(s3.equals(s1));  //false

Above code also returns false,since 'equals() method in String class has the following criteria.

  public boolean equals(Object anObject) {
if (this == anObject) {
   return true;
}
if (anObject instanceof String) { // Here it fails, StringBuffer is not a instance of String class
   String anotherString = (String)anObject;
   int n = count;
   if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
   if (v1[i++] != v2[j++])
return false;
}
return true;
   }
}
return false;

    }


The following contracts should be satisfied while overriding 'equals() method.

It is reflexive: for any non-null reference value x, x.equals(x) should return true. 
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. 
It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. 
It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. 
For any non-null reference value x, x.equals(null) should return false. 

It is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes, but vice-versa may not be true