Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Monday, 22 July 2013

Javascript Interview Questions and Answers :http://java-success.blogspot.in/2012/01/javascript-interview-questions-and_10.html


1. Difference between window.onload and onDocumentReady?
The onload event does not fire until every last piece of the page is loaded, this includes css and images, which means there’s a huge delay before any code is executed.
That isnt what we want. We just want to wait until the DOM is loaded and is able to be manipulated. onDocumentReady allows the programmer to do that.
2. What is the difference between == and === ?
The == checks for value equality, but === checks for both type and value.
3. What does “1″+2+4 evaluate to? What about 5 + 4 + “3″?
Since 1 is a string, everything is a string, so the result is 124. In the second case, its 93.
4. What is the difference between undefined value and null value?
undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value.
Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
Unassigned variables are initialized by JavaScript with a default value of undefined. JavaScript never sets a value to null. That must be done programmatically.
5. How do you change the style/class on any element?
document.getElementById(“myText”).style.fontSize = “20″;
-or-
document.getElementById(“myText”).className = “anyclass”;
6. What are Javascript closures?When would you use them?
Two one sentence summaries:
* a closure is the local variables for a function – kept alive after the function has returned, or
* a closure is a stack-frame which is not deallocated when the function returns.
A closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after the function has returned. A closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created.
The following code returns a reference to a function:
function sayHello2(name) {
var text = ‘Hello ‘ + name; // local variable
var sayAlert = function() { alert(text); }
return sayAlert;
}
Closures reduce the need to pass state around the application. The inner function has access to the variables in the outer function so there is no need to store the information somewhere that the inner function can get it.
This is important when the inner function will be called after the outer function has exited. The most common example of this is when the inner function is being used to handle an event. In this case you get no control over the arguments that are passed to the function so using a closure to keep track of state can be very convenient.
7. What is unobtrusive javascript? How to add behavior to an element using javascript?
Unobtrusive Javascript refers to the argument that the purpose of markup is to describe a document’s structure, not its programmatic behavior and that combining the two negatively impacts a site’s maintainability. Inline event handlers are harder to use and maintain, when one needs to set several events on a single element or when one is using event delegation.
1
<input type="text" name="date" />
Say an input field with the name “date” had to be validated at runtime:
1
document.getElementsByName("date")[0].
2
                   addEventListener("change", validateDate, false);

3

4
function validateDate(){

5
// Do something when the content of the 'input' element with the name 'date' is changed.
6
}
Although there are some browser inconsistencies with the above code, so programmers usually go with a javascript library such as JQuery or YUI to attach behavior to an element like above.
8.  What is Javascript namespacing? How and where is it used?
Using global variables in Javascript is evil and a bad practice. That being said, namespacing is used to bundle up all your functionality using a unique name. In JavaScript, a namespace is really just an object that you’ve attached all further methods, properties and objects. It promotes modularity and code reuse in the application.
9.  What datatypes are supported in Javascript?
Number, String, Undefined, null, Boolean
10. What is the difference between innerHTML and append() in JavaScript?
InnerHTML is not standard, and its a String. The DOM is not, and although innerHTML is faster and less verbose, its better to use the DOM methods like appendChild(), firstChild.nodeValue, etc to alter innerHTML content.

Like me, many have a love/hate relationship with JavaScript. Now a days, JavaScript is very popular with the rich internet applications (RIA). So, it really pays to know JavaScript. JavaScript is a client side (and server side with node.js) technology that is used to dynamically manipulate the DOM tree. There are a number of JavaScript based frameworks like jQuery available to make your code more cross browser compatible and simpler.  Firstly, it is much easier to understand JavaScript if you stop comparing it with Java or understand the key differences. Both are different technologies.

If you need more motivation to learn JavaScript, look at the Node.js, which is a software system designed for writing highly-scalable internet applications in JavaScript, using event-driven, asynchronous I/O to minimize overhead.

Q. What is the difference between Java and JavaScript?
A. Don't be fooled by the term Java in both. Both are quite different technologies. The key differences can be summarized as follows:


  • JavaScript variables are dynamically typed, whereas the Java variables are statically typed.

    1
    2
    3
    4
    var myVar1 = "Hello";         //string type
    var myVar2 = 5;               //number type
    var myVar3 = new Object( );   //empty object type
    var myVar4 = {};              //empty object type -- JSON (JavaScript Object Notation) style.

  • In JavaScript properties and methods are dynamically added, whereas Java uses a template called a class.  The myVar3 empty object dynamically adds properties and a method.

    1
    2
    3
    4
    5
    6
    myVar3.firstName = "Test1"// add a property to object
       myVar3.lastName = "Test2";   // add a property to object
       // add a method
       myVar3.someFunction = function( ) {
               //.…………
       }

  • JavaScript function can take variable arguments. You can call the function shown below  as myFunction( ), myFunction(20), or myFunction(20,5).

    1
    2
    3
    function myFunction( value ) {
       //.…. do something here
    }
    JavaScript has an implicit keyword known as the "arguments",  which holds all the passed         arguments. It also has a "length" property  as in arguments.length to display the number of         arguments. Technically an "arguments" is not an array as it does not have the methods like push, pop, or  split that an array has. Here is an example. 
           
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    myFunction(5,10,15,20);
    function myFunction(value) {
       //value is 5;
       //arguments[0] is 5
       //arguments[1] is 10
       //arguments[2] is 15
       //arguments[3] is 20
       //arguments.length is 4
    }

  • JavaScript objects are basically like name/value pairs stored in a HashMap<string,object>.

For example, a JavaScript object is represented in JSON style as shown below.

1
2
3
4
5
6
7
8
9
10
11
12
var personObj = {
         firstName: "John",
         lastName: "Smith",
         age: 25,
         printFullName: function() {
            document.write(this.firstName + "  " this.lastName);
         } ,
         printAge: function () {
            document.write("My age is: " this.age);
        }   
   }


You can invoke the methods as shown below

1
2
3
personObj.printFullName();
personObj.printAge();

  • JavaScript functions are objects as well. Like objects, the functions can be stored to a variable, passed as arguments, nested within each other, etc. In the above example, nameless functions are attached to variables "printFullName" and "printAge" and invoked via these variables. A function that is attached to an object via a variable is known as a "method". So, printFullName and printAge are methods.
  • Technically, what is done with the "add" and "sum" functions is that we have created a new function object and attached them to the variables "add" and sum. As you can see in the example below, the "add" variable is assigned to variable "demo", and the function is invoked via demo(2,5) within the "sum" function. 

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function add(val1, val2) {
        var result = val1 + val2;
        alert("The result is:" + result);
        return result;
    }
    var demo = add;
    function sum() {
       var output = demo(5, 2);
    }
    Now the above temp.js under tutorial/js folder can be invoked from an HTML file under tutorial/html as shown below.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script language="javascript" type="text/javascript" src="../js/temp.js">
    </script>
    <title>Insert title here</title>
    </head>
    <body>
        <form id="evaluate1">
           <input type="button" value="evaluate"  onclick="sum()"/>  
           <input type="button" value="evaluate2" onclick="demo(3,2)"/>  
           <input type="button" value="evaluate3" onclick="add(2,2)"/>  
        </form>
    </body>
    </html>
    This demonstrates that the functions in JavaScript are objects, and can be passed around. Every function in JavaScript also has a number of attached methods including toString( ), call( ), and apply( ). For example,   The temp2.js is stored under js_tutorial/js.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    function add(val1, val2) {
        var result = val1 + val2;
        alert("Result is:" + result);
        return result;
    }
    var printAdd = add.toString(); //converts the "add" function to string.
    function demo() {  
        alert(printAdd); //alerts the whole source code of the "add" function
    }
    The demo function can be invoked from an html.The temp2.html is stored under js_tutorial/html. 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="javascript" type="text/javascript" src="../js/temp2.js">
</script>
<title>Insert title here</title>
</head>
<body>
    <form id="evaluate1">
       <input type="button" value="evaluate"  onclick="demo()"/>  
    </form>
</body>
</html>


The printAdd cannot be invoked from the HTML because this variable stores the string representation of the source code of the "add"function and not the function itself.
  • JavaScript variables need to be treated like records stored in a HasMap and referenced by name, and not by memory address or pass-by-reference as in Java. The following code snippet demonstrates this.


    1
    2
    3
    4
    5
    var x = function () { alert("X"); }
    var y = x;
    x = function () { alert("Y"); };
    y();           // alerts "X" and NOT "Y"
    x();           // alerts "Y"

  • Java does not support closure till atleast version 6. A closure is a function plus a binding environment. closures can be passed downwards (as parameters) or returned upwards (as return values). This allows the function to refer to variables of its environment, even if the surrounding code is no longer active. JavaScript supports closure.

    In JavaScript a closure is created every time you create a function within a function. When using a closure, you will have access to all the variables in the enclosing (i.e. the parent) function.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var calculate = function(x) {   
         var myconst = 2;
         return function(y) {
             return x + y + myconst;    // has visibility to parent variable 'const'
         };
    var plus5 = calculate(5);         //plus5 is now a closure
    alert(plus5(3));                  //returns 10  i.e. x=5, y=3, myconst=2
    alert(plus5(7));                  //returns 14  i.e  x=5, y=7, myconst=2
    alert(plus5(10));                 //returns 17  i.e  x=5, y=10, myconst=2
  • Java programs can be single threaded or multi-threaded. JavaScript engines only have a single thread, forcing events like

    • Asynchronous UI Events like mouse click, focus, etc. It is asynchronous because you don't know when a user is going to click or change a text.
    • Timer functions like
      1
        
      1
      2
      3
      4
      var id = setTimeout(function, delay);    // Initiates a single timer which will call the specified function after the delay. The function returns a unique ID with which the timer can be canceled at a later time.
      var id = setInterval(function, delay);   // Similar to setTimeout but continually calls the function (with a delay every time) until it is canceled.
      clearInterval(id);                       // Accepts a timer ID (returned by either of the aforementioned functions) and stops the timer callback from occurring.
      clearTimeout(id);
    • Ajax responses asynchronously invoking a callback function when the response is sent back from the server. It is asynchronous because, you don't know how long a server will take to process the ajax request and then to send the response.

      to execute within the same thread. Even though all the above time based events appear to be run concurrently, they are all executed one at a time by queuing all these events. This also mean that if a timer is blocked from immediately executing, it will be delayed until the next possible point of execution making it to wait longer than the desired delay. This might also cause the intervals execute
      with no delay.

      Having said this, HTML5 specifies Web Workers, which is a standardized API for multi-threading JavaScript code.

    Here are the key points to remember:

    1. JavaScript variables are dynamically typed.
    2. In JavaScript properties and methods are dynamically added.
    3. JavaScript function can take variable arguments.
    4. JavaScript objects are basically like name/value pairs stored in a HashMap<string,object>.
    5. JavaScript functions are objects as well.


    Here are some working examples: For the examples shown below, the HTML files are stored under /html sub-folder and JavaScript files are stored under /js sub-folder. The console.log(…) statements are written to your browser's web console. For example, in firefox, you can view the web console via tools - Web Developer - Web Console. Make sure that the version of Firefox you use has this option. The Web Console is handy for debugging as well.

    Example 1: two input values are either added or concatenated depending on their types. If both values of type number then add them, otherwise just concatenate the values. Take note of the JavaScript keywords and functions like typeof, isNaN(..), Number(..), parseInt(..), etc. The "document" is part of the DOM tree representing an HTML document in memory. The method "getElementById(...)" will return the relevant "input" element from the DOM tree, and "value" will return the input value that was entered.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script language="javascript" type="text/javascript" src="../js/evaluate1.js">
    </script>
    <title>Insert title here</title>
    </head>
    <body>
        <form id="evaluate1">
         
         <input id="val1" type="text" value="" />
         <input id="val2" type="text" value="" />
         <input type="button" value="evaluate"  onclick="addOrConcat()"/>
          
            
         <p>
         <div id="result"></div>
         </p>
          
         
        </form>
    </body>
    </html>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    function addOrConcat() {
        var val1 = document.getElementById("val1").value;  //string
        var val2 = document.getElementById("val2").value;  //string
        var result = document.getElementById("result");    //object
         
         
        var ans = -1;  //number
         
        //if val1 and val2 are numbers, add them
        if(!isNaN(val1)  && typeof parseInt(val2) == 'number') {
            ans = Number(val1) + Number(val2);  //add numbers
        }else {
           ans = val1 + val2;                   //string concat
        }
         
        result.innerHTML = "Result is: "  + ans;
        //write to browser console.
        console.log("val1 is of type " + typeof val1);
        console.log("result is of type " + typeof result);
        console.log("ans is of type " + typeof ans);
    }
    Example 2: Very similar to Example 1, but uses objects, and passes the relevant values from the call within HTML itself. It also uses the toString( ) method to convert a function object to display its source code.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script language="javascript" type="text/javascript" src="../js/evaluate3.js">
    </script>
    <title>Insert title here</title>
    </head>
    <body>
        <form id="evaluate1">
         
         <input id="val1" type="text" value="" />
         <input id="val2" type="text" value="" />
         <input type="button" value="evaluate"  onclick="addOrConcat(document.getElementById('val1').value,document.getElementById('val2').value)"/>
          
            
         <p>
         <div id="result"></div>
         </p>
          
         
        </form>
    </body>
    </html>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    function addOrConcat(val1,val2) {
      
     var evalObj = new Object(); //create an empty object
      
     evalObj.input1 = val1;     // add a property of type string
     evalObj['input2'] = val2;  // add a property of type string
     evalObj.result = document.getElementById("result"); // add a property of type object
      
     //add a method
     evalObj.evaluate = function() {
      
          if(!isNaN(this.input1)  && typeof parseInt(this.input2) == 'number') {
              this.ans = Number(this.input1) + Number(this.input2);  //add numbers
          }else {
              this.ans = evalObj.input1 + this.input2;              //string concat
          }
         
          this.result.innerHTML = "Result is: "  + this.ans;
         
        }
         
        evalObj.evaluate(); //call the method evaluate and "this" refers to evalObj
        console.log(evalObj.evaluate.toString());
        
    }
    Example 3: Similar to Example 2, with minor modifications to the JavaScript file to demonstrate keywords like "arguments"
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    function addOrConcat() {
      
     var evalObj = new Object();                          // create an empty object
      
     evalObj.input1 = arguments[0];                       // this is value1
     evalObj['input2'] = arguments[1];                    // this is value2
     evalObj.result = document.getElementById("result");  // add a property of type object
      
     //add a method
     evalObj.evaluate = function() {
      
          if(!isNaN(this.input1)  && typeof parseInt(this.input2) == 'number') {
              this.ans = Number(this.input1) + Number(this.input2);  //add numbers
          }else {
              this.ans = evalObj.input1 + this.input2;              //string concat
          }
         
          this.result.innerHTML = "Result is: "  + this.ans;
         
        }
         
        evalObj.evaluate(); //call the method evaluate and "this" refers to evalObj
        console.log(evalObj.evaluate.toString());
        
    }

    JavaScript Interview Questions and Answers: Working with the objects

    Q. What are the built-in objects in JavaScript?
    A. String, Date, Array, Boolean, and Math.


    Q. What are the different ways to create objects in JavaScript?
    A.


    • By invoking the built-in constructor.

    1
    2
    3
    4
    5
    6
    7
    var personObj1 = new Object(); // empty object with no properties and methods.
    personObj1.name = "John"  ;     //add a property
    personObj1.status = "Active";     //add a property
    //add a method by associating a function to variable isActive variable.
    personObj1.isActive = function() {
         return this.status;


    • By creating a constructor (i.e. a template), and creating an object from the constructor. The Person constructor is like any other function, and it is a convention to start the function name with an uppercase letter to differentiate it with other functions.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function Person(name, status) {
        this.name = name;
        this.status = status;
        //add a method by associating a function to variable isActive variable.
        personObj1.isActive = function() {
           return this.status;
        
        
    }
     
    var personObj1 = new Person("John", "Active");

    • Creating the object as a Hash Literal. This is what used by the JSON, which is a subset of the object literal syntax.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var personObj1 = { };    // empty object
     
    var personObj2 = {
     
       name: "John",
       status: "Active",
       isActive: function() {
           return this.status;
       
      
    };

    Q. Does JavaScript has a built-in concept of inheritance?
    A. It does to some extent. You can think of every object as inheriting from it's "prototype".

    Q. What is a "prototype" property?
    A. A prototype is a built-in property of every JavaScript object. For example,

    1
    2
    3
    var personObj1 = new Object();  // empty object with no properties and methods.
    personObj1.name = "John"  ;     //add a property
    personObj1.status = "Active";   //add a property


    Now, if you create another person object as shown below, all the properties will be empty, and needs to be reassigned.

    1
    2
    3
    var personObj2 = new Object();  // empty object with no properties and methods.
    personObj2.name = "John"  ;     //add a property
    personObj2.status = "Active";   //add a property

    What if you want to set all the Person object status to be "Active" by default without having to explicitly assign it every time? This is where the "prototype" property comes in handy as shown below.

    1
    2
    3
    4
    5
    6
    7
    var personObj1 = new Object();            //empty object with no properties and methods.
    personObj1.name = "John"  ;               //add a property
    personObj1.prototype.status = "Active";   //add a prototype property that will set "Active" as the default
     
     
    var personObj2 = new Object();  // empty object with status="Active" will be created.
    personObj2.name = "John"  ;     // add a property



    When you create an object via a constructor as in var personObj1 = new Person("John", "Active"), the prototype property is also set. When you actually create an object via a constructor, the new operator actually performs the following tasks.

    STEP 1: Creates an empty object as in var personObj1 = new Object();

    STEP 2: Attach all properties and methods of the prototype of the function to the resulting object.

    STEP 3: Invoke the function "Person" by passing the new object as the "this" reference.


    It is important to understand that, all the objects that are created via a constructor function will have the same prototype. This means, if you modify any one object that has been created via the constructor, you will be modifying all the objects that have been created and the new ones you will be creating via the constructor function. You can think of this as every object is inheriting from it's prototype. So, the above approach of individually adding to some properties as in

    1
    personObj1.prototype.status = "Active";

    can be very handy for methods and constants, and this "prototype" approach is used by many JavaScript frameworks.

    Q. What are some of the best practices relating to coding with JavaScript?
    A.

    • Use proven frameworks like jQuery, EXT JS, etc to ensure cross browser compatibility, and quality code.

    • Provide a clean separation of content, CSS, and JavaScript. This means store all Javascript code in external script files and build pages that do not rely on Javascript to be usable.


      Instead of:


      1
      <input id="btn1" type="button" value="click-me1" onclick="test()"/>

      Use:

      1
      <input id="btn1" type="button" class="something" value="click-me1" /> 

      The above page snippet does not depend on the JavaScript function. The JQuery function below

      1
      2
      3
      4
      $('input.something').click(function(){
          //do something here
          alert('The button is clicked');
      });


      jQuery allows you to easily attach a click event to the result(s) of your selector. So the code will select all of the <input /> tags of class “something” and attach a click event that will call the function.

      Also instead of

      1
      2
      if(someCondition)
          document.write("write something ........... ");

      Use:

      1
      <div title="something"> ... </div>


      1
      2
      var titleElement = $('div[title="something"]');
      titleElement.text('Better Approach');

      The above page is renedred as 100% (X)HTML without requiring the JavaScript to write something.



    • Use code quality tools like JSLint.

    • Use unit testing frameworks like Jasmine, qUnit, etc.


    • Use "===" instead of "==". If two operands are of the same type and value, then === produces true and !== produces false. If you use "==" or !="" you may run into issues if the operands are of different types.


    • Avoid using the eval(…) function as it poses a security risk and can also adversely affect performance as it accesses the JavaScript compiler.


    • Namespaces are essential for avoiding type name collisions. JavaScript does not have packages as in Java. But in JavaScript, this can be simulated with empty objects. For example


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    var MyPage1 = { };   // empty object acting as a namespace
     
    MyPage1.Person = function(name, status) {
        this.name = name;
        this.status = status;
    }
     
    MyPage1.Person.protoyype  =
     
    {
        isActive: function() {
             return this.status;
        }
     
    }
     
     
    var personObj1 = new MyPage1.Person("John", "Active");
    console.log(personObj1.isActive());


    • Simulate encapsulation with Douglas Crawford's approach as shown below as JavaScript does not have access modifiers like private, protected, etc as in Java.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    function Person(name, status) {
          this.get_name = function( ) { return name; }
          this.get_status = function( ) {return status; }
    }
     
    Person.prototype.isActive = function( )
    {
          return this.get_status();
    }
     
     
    var personObj1 = new Person("John","Active");
    console.log(personObj1.isActive( )) ;
    1
      
    1
      
    • Favor the JavaScript literal way with { … } as opposed to the new Object() to create new objects as the literal way is much more robust and also makes it simpler to code and read.
    1
     
    • Favor [ ] to declare an array as opposed to an array object with new Array( ). For example,
    1
    2
    3
    4
    5
    6
    var vehicles = ['Car', 'Bus'] ; // creates an array
     
     
    var vehicles = new Array( ); // creates an array object
    vehicles[0] = ''Car" ;
    vehicles[1] = 'Bus' ;


    • Favor using semicolons (;), and use comma separated variables as opposed to repeating vars. For example


    1
    2
    3
    4
    5
    6
    //okay
    var x = 5;
    var y = 6;
    var z = 9;
     
    var x =5, y=6,z = 9; // better
    1
      
    1
    Use console.log(...) as oppose to alert(...); for debugging.

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...