Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Friday, November 8, 2013

New to JavaScript - Tryout Google chrome + F12 = JavaScript Console

If you are a beginner, and want to try out some Java script code , you can think of Google Java script console. This comes with Google chrome browser.


Just press F12 to launch in js console.

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

Friday, May 17, 2013

JavaScript Learning #6 - Ways to call a function

This article helps in understanding the importance of  "this", global objects and ways to call a function.

Very nice article @ http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx


Examples:


//Type#1 :
function makeArray(arg1, arg2) {
return [this, arg1, arg2];
}
makeArray("one", "two"); //output: window, one, two
window.makeArray("one", "two"); //output: window, one, two


alert( typeof window.methodThatDoesntExist );
// => undefined
alert( typeof window.makeArray);
// => function


//Type#2: creating the object
var arrayMaker = {
myName: 'Kondal Kolipaka',
make: makeArray
};
arrayMaker.make("one", "two");  //output: [arrrayMaker, one, two]
arrayMaker['make']("one", "two");  //output: [arrrayMaker, one, two]



//Type#3 : 
var arrayMaker2 = {
myName: 'Kondal Kolipaka',
make: function (arg1, arg2) {
    return [this, arg1, arg2];
}
};
arrayMaker2.make("one", "two"); //output: arrayMaker2, one, two



//Type#4
(function () {
   function make(arg1, arg2) {
       return [this, arg1, arg2];
   }
   alert(typeof make);
   // function

   alert(typeof this.make);
   // undefined

   alert(typeof window.make);
   // undefined
})();

alert(typeof make);
// undefined

alert(typeof this.make);
// undefined

alert(typeof window.make);
// undefined


//Type#5
(function(){
/* code */
}());

(function(){
/* code */
})();



Thursday, May 16, 2013

JavaScript Learning #5 - Extending Built-In Objects with Prototype

Prototype can also be used to extend JavaScript's built-in objects.
The displayed code uses an anonymous function to add the negate property to JavaScript's Number type; the new property reverses the sign of any numeric value.

Example:


var myValue = 345.62;

Number.prototype.negate = function() {
return -1* this;
};
console.log(myValue.negate());

Number.prototype.half = function() {
return this/2;
};

console.log(myValue.half());


Output:
-345.62

172.81

JavaScript Learning #4 - Using the 'prototype' keyword


A big advantage of using objects is the ability to re-use already-written code in a new context. JavaScript supports extending and inheriting objects via the prototypekeyword

Example:


function Person(personName){
this.name = personName;
this.info = "This person is called " + this.name;
this.showInfo = function(){
console.log(this.info);
};
}

Person.prototype.sayHello = function(){
console.log(this.name + " says Hello");
};

var name = prompt("Who are you?");
person1 = new Person(name);

person1.showInfo();
person1.sayHello();


Output:

This person is called kkondal
kkondal says Hello


JavaScript Learning #3 - Using a Constructor Function

An object constructor function creates a kind of 'template' from which other, similar objects can be created.

Example:


function Person(personName){
this.name = personName;
this.info = "I'm a person called " + this.name;
this.showInfo = function(){
console.log(this.info);
};
}

var name = prompt("Who are you?");
person1 = new Person(name);

// add code to create another Person object called person2, again via a prompt
// You'll need code similar to the two lines above.

function Person2(personName) {
    this.name = personName;
    this.info = "I am person called "+ this.name;
    this.showInfo = function () {
      console.log(this.info);  
    };
    
}

var name2 = prompt("Who are you buddy??");
var person2 = new Person2(name2);

person1.showInfo();
person2.showInfo();


Output:


I'm a person called kondal
I am person called kolipaka

JavaScript Learning #2 - Creating a new Object



**
 *  JS has built in object simply called "Object", which you can     use as a kind of blank canvas for creating any new object.
 * example:
 * my newcar = new Object();
 * newcar.color = "red";
 *
 * /


var manager = new Object();

//Assigning variable
manager.role = "People management";

function Team () {
    console.log ("Team has been called");
}

//Assigning function
manager.team = Team;


console.log("Manager role "+ manager.role);
console.log(manager.team());



Output:
Manager role People management
Team has been called

Wednesday, May 15, 2013

JavaScript Learning #1 - undefined

Just for my reference!!

Very well explained about 'undefined' usage in JavaScript.  Source is from @Mozilla.

Examples:

Test#1:

function xx() { 
  var x; 
if (x == undefined) {
window.alert("undefined called"); 

else { 
window.alert("Not called");
}
}

xx();

output: "undefined called" window will popup.


Test#2:

function xx() { 
  var x = null; 
if (x == undefined) {
window.alert("undefined called"); 

else { 
window.alert("Not called");
}
}

xx();

output: "undefined called" window will popup.



Test#3:

function xx() { 
  var x = 10; 
if (x == undefined) {
window.alert("undefined called"); 

else { 
window.alert("Not called");
}
}

xx();

output: "Not called" window will popup.



Test#4:

function xx() { 
  var x = null; 
if (typeof x == undefined) {
window.alert("undefined called"); 

else { 
window.alert("Not called");
}
}

xx();

output: "Not called" window will popup.


------------------------------------------------------------------------------------------------------


Summary

The value undefined.
Core Global Property
Implemented inJavaScript 1.3
ECMAScript EditionECMAScript 1st Edition

Syntax

undefined 

Description

undefined is a property of the global object, i.e. it is a variable in global scope.
The initial value of undefined is the primitive value undefined.
Starting in JavaScript 1.8.5 (Firefox 4), undefined is non-writable, as per the ECMAScript 5 specification.
A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned.
You can use undefined and the strict equality and inequality operators to determine whether a variable has a value. In the following code, the variable x is not defined, and the if statement evaluates to true.
1
2
3
4
5
6
7
var x;
if (x === undefined) {
   // these statements execute
}
else {
   // these statements do not execute
}
Note: The strict equality operator rather than the standard equality operator must be used here, because x == undefined also checks whether x is null, while strict equality doesn't. null is not equivalent to undefined. See comparison operators for details.
Alternatively, typeof() can be used:
1
2
3
4
var x;
if (typeof x === 'undefined') {
   // these statements execute
}
One reason to use typeof() is that it does not throw an error if the variable has not been defined.
1
2
3
4
5
6
7
8
// x has not been defined before
if (typeof x === 'undefined') { // evaluates to true without errors
   // these statements execute
}
if(x === undefined){ // throws a ReferenceError
}
However, this kind of technique should be avoided. JavaScript is a statically scoped language, so knowing if a variable is defined can be read by seeing whether it is defined in an enclosing context. The only exception is the global scope, but the global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object (using the in operator, for instance)