Saturday, November 10, 2012

A short guide to Java Script

Java Script

  • Also referred to as JS or Js.
  • JavaScript is the scripting language of the Web.
  • Major Aim was to energize and enhance the user's web experience.
  • Inspired by SELF programming language.
  • Object based, Interpreted, scripting language. The part of the web browser that runs the java script is called JavaScript Interpreter.
    • JavaScript is object based and not object oriented because it doesn't support Inheritance and Polymorphism. It have built-in objects like windows etc.
  • JavaScript does not use classes. JavaScript is prototype based, not class based.
  • Created by Brendan Eich at Netscape in December 1995. (Earlier it was called "LiveScript" before that it was called "Mocha").
    • European Computer Manufacturer's Association (ECMA) standardized the script and named it as ECMAScript.
  • JavaScript can be divided into three parts - 
    • Core Language (language fundamentals and syntax), 
    • Client-side (provides access to DOM and various browser objects) and 
    • Server-side (to code for server side standalone components of web application, access to server side objects). 
  • Client-side JavaScript is interpreted on the fly by the browser while Server-side JavaScript is first compiled into bytecode like Java. 
  • Server-side JavaScript is not covered here.
Features
  • JavaScript provides client side validations, so we are saved from passing data to server and reloading the page. Prior to JavaScript dynamic behavior was achieved with Server-side scripting.
  • JavaScript is case-sensitive.
  • A script can get the height and width of the browser window, client date as well as history of visited pages.
  • Alternate text can be provided, for occasions when JavaScript  support is absent or disabled with <noscript> </noscript>.
  • Cookie data is stored in the DOM document object's cookie property as one or more "name=value" pairs, in which the values may not contain any whitespace, commas, or semi-colon characters. 
  • Cookies can be set using document.cookie as well as readCookie and writeCookie method.
  • escape() and unescape() methods are used to encode/decode the strings - remove whitespace, etc other characters.
JavaScript and Security Concerns:
  • JavaScript doesn't allow you to read/write files on the user's hard drive. This limitation wipes out the potential for a lot of viruses. JavaScript doesn't support File Handling.
  • JavaScript doesn't support Network programming. It cannot establish a direct connection to any other hosts on the network. JavaScript program cannot use a client's machine as an attack platform from which to attempt to crack passwords on another machine.
  • Most browsers don't allow scripts to open or close windows without the user's approval. 
  • A JavaScript program cannot close a browser window without user confirmation unless it opened the window itself.
  • Access to cookies is restricted by owning websites.
  • JavaScript cannot be used to set the value attribute of a file input, and will not be allowed to use them to upload files without permission.
  • JavaScript cannot read what locations a user has visited by reading them from the location object, although it can tell the browser to jump back or forward any number of steps through the browser history. It cannot see what other Web pages the user has open.
  • It cannot see when the user interacts with other programs, or other parts of the browser window.
  • It cannot open windows out of sight from the user or too small for the user to see. JavaScript doesn't allow to open or resize the window to less than 100px.
  • A script may not cause a window or frame to display an about: URL, such as about:cache, because these URLs can expose system information, such as the contents of the browser's cache.
  • JavaScript is used as a "script engine" for other software components, such as ActiveX controls in Internet Explorer and plugins in Netscape. These may have file access and networking access.

<Script> Tag
  • Can be added anywhere in HTML, but its best to put it in <head> tag.
  • "type" attribute identifies the type of scripting language. Other scripting language examples are VBScript, ASP.Net AJAX etc. It actually specifies MIME type.
  • In addition to <script> tag, JavaScript code can be put directly into event handlers as well, its not a good practice and is done normally in case of a single line of code like an alert.
    <script type="text/javascript">
    function ...
    ....
    </script>

    <script type="text/javascript" src="myCustomJS.js"> </script>


Event
  • JavaScript mechanism that allows you to trigger a piece of JavaScript when something of interest happens to the page.
  • Events are initiated by users but they come from browser.
    <h1 onclick="alert('Hello');">Click Here</h1> //executing JS code
    <h1 onmouseover="change()">Hello</h1> // calling JS function
    document.getElementById("submitButton").onclick=displayName();
    document.getElementById("submitButton").onclick=function(){
        changeName();
        displayName()
    };
  • JavaScript event object has properties for type, target, altKey/shiftKey/ctrlKey gives true/false based on if for alt/shift/ctrl key was pressed, charCode/keyCode provides ascii code in case of KEY-related events etc
Event - Standard Event Model
  • With events defined in above section, we cannot Add and Remove Event listeners, Standard Event Model provides us ways to add/remove (attach/detach) event listeners.
    element.addEventListener(<type>, <JSFunction>, <use Capture>);
    element.removeEventListener(<type>, <JSFunction>, <use Capture>);
    element.attachEvent(<type>, <JSFunction>); // Old IE browser
    element.detachEvent(<type>, <JSFunction>); // Old IE browser
  • Bubbling is default behavior. (Google Bubbling and Capture for more information).
JavaScript variables, constants and data types
  • Three basic data types: string, number and boolean.
  • There are two other data types: function and object.
  • Data type are assigned to variables automatically depending on the value assigned, it changes with the change in value.
  • All numbers in JavaScript are stored as 64-bit (8-bytes) base 10, floating point numbers. There is no concept of int, long, and float.
  • false isn't exactly same as 0, but it converts to 0 when used where a number is expected.
  • The current variable type can be revealed by the typeof keyword. It returns a value of "undefined" for uninitialized variables.
  • Number.NaN, Number.POSITIVE_INFINITY, NUMBER.NEGATIVE_INFINITY, isNaN(), isFinite() are some key properties and methods.
JavaScript Functions
  •  There are two ways to define functions - 
    A. Using Function declaration:
    function test()
    {
       alert(test function);
    }

    B. Using Function expression (Assigning anonymous function to a variable):
    var test2 = function()
    {
       alert(test function);
    }
  • Approach B demonstrate that functions are variables in JavaScript. This approach is revisited in JavaScript objects.
  • Approach A on using function declaration are loaded first in the programs. Java script engines hosts function declaration to the top. It is possible to call the function before its declaration. It is not the case with function expression, it'll throw error.
    test();  // This will not error out and work normally.
    test2(); // This will error out 
             // because function expressions are not loaded first. 
    function test()
    {

       alert(test function);
    }
    var test2 = function()
    {

       alert(test function);
    }
  • A function can return another function.
    function testFunc(name)
    {
       return function()
       {
          var message = "Hello "+ name;
          alert(message);
       };
    }

    var func = testFunc("Prince");
    func();
  • To have variable arguments functions - use arguments keyword.
    function sum()    {
 
       total = 0;
 
       for (i=0; i < arguments.length;  i++)
 
       {
 
           total += arguments[i];
 
       }    }    var sumTotal = sum(100, 1, 2, 4);    document.write(total);
Objects
  • Memory area created by browser which represents an entity.
  • Almost everything is object in JavaScript in Java Script, ex Forms, Text field etc.
  • There are three ways to create objects:-
    • Define and create a direct instance of an object.
        <script>
            function customToString()
            {
                return this.firstname+" "+this.lastname;
            };

            var emp=new Object();
            emp.firstname="Prince";
            emp.lastname="Kapoor";
            emp.ID=7918;

            emp.customToStr = customToString;
            document.write(emp.customToStr());
   
    </script>
    • Using JSON to define an object.
JSON Ex 1:<script>
            var emp={firstname:"Prince",lastname:"Kapoor",ID:7918};
            document.write("Employee ID of "+emp.firstname + " is " + emp.ID);
        </script>

JSON Ex 2:<script>
            var emp=
            {  firstname:"Prince",
               lastname:"Kapoor",
               ID:7918,
               getOutputText: function() {
                  return "Employee ID of "+this.firstname + " is " +this.ID;
               }
            };
            document.write(emp.getOutputText());
        </script>
    • Using a prototype function to define an object, then create new object instances. (MOST PREFERRED)
      • By naming conventions, functions starts with small letter and constructors start with Capital letter.
Syntax: function object-name (param1, param2, param3)    
        {
            this.property1 = param1;
            this.property2 = param2;
            this.property3 = param3;
            this.method1 = function1;
            this.method2 = function2;
        }

Ex:     function Emp(firstname,lastname,id)
        // Above declaration could also be written as:
        // var Emp = function(firstname, lastname, id)
        {
            this.firstname=firstname;
            this.lastname=lastname;
            this.ID=id;
            this.getFullName = function ()
            {
                return this.firstname+" "+ this.lastname;
            }

        }

        var prince = new Emp("Prince", "Kapoor", 7918);
  • When we need multiple objects, then we can also use factory functions, but using constructors are a better idea.
    • With Factory methods also, in case we need to modify an object interface, we need to make changes at one place, like adding a new function to the object.
         function createEmp(firstName, lastName) {
             return {
                 firstName : firstName, 
                 lastName : lastName,
                 getFullName : function () {
                     return this.firstName+" "+ this.lastName;
                 }
             };
         }
         var prince = createEmp ("Prince", "Kapoor");
  • The way we have defined functions above, including defining in the constructor is not the best way as it stores function definition in the memory separately for each object.
    • If we define it using the prototype then function definition will be stored only once.
    • Functions defined for Date, String etc JavaScript objects are also defined in the same way.
Ex.      function Emp(firstname,lastname,id)        {
            this.firstname=firstname;
            this.lastname=lastname;
            this.ID=id;
        }
        Emp.prototype.getFullName = function ()
        {
            return this.firstname+" "+ this.lastname;
        }
  • By using apply(newObject) on function method, function can be executed as if it is part of another object.
        function Emp (firstname,lastname,id)
        {
            this.firstname=firstname;
            this.lastname=lastname;
            this.ID=id;
            this.getFullName = function (salutation)
            {
                return salutation+" "+this.firstname+" "+ this.lastname;
            }
        }

        function Person(firstname,lastname)
        {
            this.firstname=firstname;
            this.lastname=lastname;
        }

        var emp1 = new Emp("Prince", "Kapoor");
        var person1 = new Person ("Jai", "Bhaskar");
        document.write(emp1.getFullName.apply(person1, ["Mr."]));
  • In Apply we pass arguments as array and there is call() method, in which we pass arguments directly without any array.
        document.write(emp1.getFullName.call(person1, "Mr."));
  • Following is practical example of apply/call - using methods of Array on arguments object.
        Array.prototype.pop.apply(arguments);
  • Objects are very flexible and can be extended using prototype property to add more object properties or methods.
  • " prototype " extends object definition using its name, not instance name.
DOM:
  • Is an API for accessing and changing content, style document structure.
  • The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document. DOM is separated into 3 parts - Core DOM, XML DOM, HTML DOM. HTML DOM is standard object model for HTML. 
  • The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
  • When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is constructed as a tree of Objects. 
  • Window
    • Represents content area of the browser.
    • There are three types of dialog message communications: window.alert(), window.confirm(), and window.prompt()
    • window.open() is used to open a new window object.
    • window.moveTo()to move the current window.
    • window.document represents HTML document.
    • Object Type is DOMWindow.
    • Window object has two self-referential properties, window and self. Either of these global variable to refer directly to the Window object. Ex. self.close().
    • window.top refers to the top-most window in case of multiple frames.
    • window.self is mostly used in comparisons like: 
      • window.parent.frames[0] != window.self 
      • window.self != windpow.top
  • Navigator
    • Accesses browser program, version etc.
    • window.navigator.appCodeName,window.navigator.appName, window.navigator.platform, window.navigator.appVersion (in some cases appMinorVersion as well), window.navigator.userAgent, navigator.systemLanguage, navigator.cookieEnabled
    • navigator.javaEnabled() for checking if java is enabled.
  • Screen
    • Updates about physical environment in which browser is running, pixels height width etc.
    • Some key properties related to client screen are : window.screen.width, window.screen.height, window.innerWidth, window.innerHeight, window.screen.availWidth, window.screen.availHeight, and window.screen.colorDepth
  • History
    • For accessing browser history information.
    • window.history stores history information as an array.
    • history.back(), history.forward(), history.go() are key methods in history object.
  • Location
    • Maintains URL information of the page.
    • window.location object has 5 properties containing the components of full URL: location.href, location.protocol, location.host, location.pathname, location.hash
    • Assigning a new URL to the location property will cause the browser to load new page.
    • reload() method will cause the page to be reloaded.
    • replace() method replaces the history entry.
    • location.assign() method loads a new document.
      window.location.assign("http://www.princekapoor82.blogspot.com")
  • Document
    • Represents the HTML document.
    • Some key properties related to browser screen size are: document.body.clientWidth, document.body.clientHeight
    • document.title, document.URL(shows same information as location.href but not used for navigation), document.domain (similar to location.host), document.lastModified and document.referrer are some of the key properties.
    • document.write(), document.getElementById(), getElementByTagName(), getElementsByClassName() are some of the most frequently used methods.
    • write() vs CreateElement()
      • write cannot be used to add new components once the page has been loaded as write will remove the page content and then write its content.
      • write is mostly used during page load.
    • document object has properties (arrays) for child objects for forms, anchors, images, and links. Each of these objects is an array and contains items in the order in which they appear in the document. Please note: Images that are incorporated as part of the CSS Style are not part of images array, only images defines with <img> will constitute the array. These arrays are older ways of accessing the components, now getElementBy*() methods are supposed to be used.
    • form object has its own child elements for all the form elements.
    • Every form field has a form object that can be passed along to a function.
            onClick="validateDate(this.form)"

            function validateDate(form)
            {
                //Value of any field can be accessed using syntax:  
                form["StartDate"].value
            }
      • This approach of accessing data is same as getElementById() - It just makes code more readable.
      • Just like passing form object using this.form, you can pass form field object with this keyword. Ex
                onClick="validateDate(this)"
      • All the presentational DOM properties are contained within a parent style property, which is a child of the object. For ex. obj.style.textAlign 
    • To add/remove elements following methods can be used: document.createElement, document.createTextNode, <dom object reference>.appendChild, <parent dom object reference>.removeChild(<child dom object reference>);
Form Validation
  • Forms are used to collect information from websites checkboxes, textboxes, Buttons, dropdowns etc.
  • JavaScript can be used to validate data in HTML forms before sending off the content to a server.
Number & String
  • JavaScript numbers are stored as double precision floating point numbers.
  • parseInt("4 Apples") returns 4.
  • "10" == 10.0 returns true.
  • String (aNumber) converts number to string.
  • Number (aString) converts string to number.
  • "Prince" > "Kapoor" returns true because it evaluates based on ASCII.
  • To convert decimal to binary, octal, hexa-decimal, use toString method with appropriate base as parameter:
    var myNumber=16;
    document.write(myNumber.toString(16))   // prints 1
    document.write(myNumber.toString(8))    // prints 2
    document.write(myNumber.toString(2))    // returns 10000
  • Auto type casting of numbers to text happens when we use then in Alert (Alert expects text).
  • Text Strings must be enclosed within double quote, nested inner string should be enclosed within single qoute.
  • There is a discrepancy in floating point calculations in Java and JavaScript. Check the result of 15 * 81.66 or 0.7 * 5000 or 0.2 + 0.1.
  • Infinity is a special number, 1/0 is Infinity. (Infinity == var)
  • NaN - 1/"abc" is NaN, isNan()is used to check if parameter is a number or not.
  • Key Properties of Number - MAX_VALUE, MIN_VALUE, NEGATIVE_INFINITY, POSITIVE_INFINITY, NaN
  • Key Methods of Number - toExponential(), toFixed(), toPrecision(), toString(), valueOf()
  • String Key Property - length
  • String Key Methods - charAt(), charCodeAt(), concat(), fromCharCode(), indexOf(), lastIndexOf(), localeCompare(), match(), replace(), search(), slice(), split(), substr(), substring(), toLowerCase(), toUpperCase(), toString(), trim(), valueOf().
Image
  • Refers to images on the HTML screen (<img> tag).
  • Primarily used to pre-cache/pre-loading images based on some action/event. This helps in getting better response time.
  • To pre-load an image, we create a new Image() object in JavaScript and pass the URL of the image.
Array
  • There are three ways to create an array:
    1.
    var fruits = new Array();
   
fruits[0]="Orange";
    fruits[1]="Apple";
    fruits[2]="Banana";

    2.
    var fruits = new Array("Orange", "Apple", "Banana"); 

    3.
    var fruits = ["Orange", "Apple", "Banana"];
    var productList = []; // will create empty array.
  • Commonly used methods - length(), indexOf(), lastIndexOf(), concat().
  • Other operations methods - toString(), join(), slice(), splice(), reverse(), sort(), push(), pop(), shift(),
  • Array object has some interesting methods - every(), some(), filter(), forEach(), map()
    • These methods are passed callback function as parameter.
    • every() is equivalent of for all.
    • some() is for atleast one.
    • filter() creates a new array with items that match the criteria.
    • forEach() doesn't return anything, just executes the function on every element withing an array.
    • map() similar to forEach but returns the updated elements in a new array.
      • ex. arrayVar.every(arrayOfEvenNumbersTestFunc);
      • signature of callback function - 
        • arrayOfEvenNumbersTestFunc(value, index, array);
Operators
  • = = = and ! = = should be used to check equality and inequality. = =  and ! = may produce unexpected results. For Example - (true = = 1) will return true while (true = = = 1) will return false. = = = and ! = = doesn't perform type coercion.
  • Switch works fine for number, string, as well as boolean.
  • typeof operator can be used to get the type of the operand. Ex of types - "object", "boolean", "function", "number", "string", "undefined".
    • Ex. typeof var == "string".
  • instanceOf operator is used to if a variable is an instance of a Object
    • Ex. prince instanceOf Emp
Cookie
  • Distinct information delivered by web server to browser when they interact for the first time.
  • For basics of Cookie - refer to Key Internet Terms.
  • document.cookie is the cookie property.
DOM and CSS
  • All the presentational DOM properties are contained within a parent style property, which is a child of the object. For ex. obj.style.textAlign 
  • style.visibility is used to toggle visibility ("hidden"/"visible").
  • Variable declared without a value will have the value undefined. null and undefined are different.

Timers and Animation
  • There are following methods related to timer event
    • setInterval()
      • Executes a function repeatedly after a specified time interval.
      • myTimerVar=setInterval(<javascript function>,milliseconds);
    • setTimeOut()
      • Executes a function once after a specified time interval.
      • myTimerVar=setTimeOut(<javascript function>,milliseconds);
    • clearInterval()
      • Clears interval set with setInterval() to stop further executions.
      • clearInterval(myTimerVar);
    • clearTimeOut()
      • Same as clearInterval() to stop timer set with setTimeOut().
      • clearTimeOut(myTimerVar);

JavaScript Local Storage
  • Designed to hold key/value pairs.
  • Can only be accessed by JS window object.
    localStorage.userName = "Prince"; // stores userName.
    localStorage.setItem("LastName", "Kapoor"); // works same as above.
    localStorage.removeItem("userName"); // removes userName.
    localStorage.clear(); // clears all properties
  • Values stored in LocalStorage are always of type string.
  • JSON can also be used to store/retieve objects in LocalStorage.
  • LocalStorage is restricted to a domain.
Important Notes:
  • Alert() is technically method of windows object, it can also be called as windows.alert()
  • Script data gets refreshed on refreshing the web page.
  • To encode URI parameter (remove spaces and special characters), we have encodeURIComponent(). We normally encode for parameter and value.
  • obj.innerHTML !== "undefined" can be used to test if obj is a DOM object.
  • If "new" keyword is missing in object creation, then object properties defined with "this"  will be created in window object.
  • You can redeclare a variable, it'll not loose its value.
    var name="Prince";
    var name;
  • To prevent links from refreshing or loading another page, we can use the JavaScript void() function and pass a parameter of 0 (zero) and #.
    <a href="JavaScript:void(0);" onClick="alert('Testing Void(0)')">Click</a>
  • There is a special "for in" loop that can be used to list all the initialized properties and methods of an object (including DOM objects like windows etc). It can also be used for arrays (since arrays are also objects).
  • RegExp - Object to support regular expression.
  • The \n escape sequence is used to specify a newline character in the alert dialog text. 
  • KEYPRESS event doesn't capture modifier keys like Shift, Ctrl etc. KEYDOWN and KEYUP does capture.

Callback Functions

Inline JavaScript code and JavaScript functions can be assigned to any HTML event attribute, such as onClick, onLoad etc. 
<img id="update" src="updateImg.jpg" onClick="updateNavigation(3);">

Above approach mixes HTML and JavaScript, which intrudes structural nature of the HTML elements and increases maintainance and debugging efforts

We should keep the intergation of JavaScript and HTML to JavaScript itself. Following are some examples:

<body onload="initDetails();">
can be written in JavaScript as
windows.onload=initDetails; in the <HEAD> section.

<body onload="initDetails("read_only");"> 
can be written in JavaScript as
windows.onload = function(evt) { initDetails("read_only"); }

AJAX and JavaScript
  • AJAX can write script that request information from the server and then process and display that information on the page.
  • AJAX is not a technology but simply a new approach towards dynamic user interface combining other technologies.  
JavaScript Object Reference
  • JavaScript Object Reference will be helpful for coding in JavaScript. Reference will provide all the methods and properties available in an object.
Some Javascript examples:-

    Restricting users with what keys can be entered - 
    Check on key press event with the ascii code of the key pressed, if key is one of the restricted keys, then prevents default action.
 
    Implement Hot Keys - 
    event -> keyDown
    event.ctrlKey should be true.
    Compare ascii code to check if the key down is the key which we need to capture for hot keys.