Google

Jan 27, 2012

JavaScript Interview Questions and Answers: Coding and putting all together

Q. How would you go about implementing a mechanism to log clien-side JavaScript errors to the server-side log?

A. Generally a Web application will log any exceptions that occur during server-side processing. These logs are key in identifying and debugging issues with the application. But when you build rich client-side applications with lots of JavaScript code, it is really worth implementing a mechanism to log all the client side errors to the server side. The following code sample demonstrates an AJAX POST being made from the client side to the server side with the data -- error msg, the URL of the JavaScript file, and the line number where the error occured.

(function () {
    'use strict'; // throws more xecpetions, prevents, or throws errors, when relatively "unsafe" actions are taken such as accessing global object, 
                 // and disables features that are confusing or poorly thought out.

  //Return if the project and module are already present
  if (window.MYPROJECT && window.MYPROJECT.errorHandler) {
   return;
  }
 
 // Create MYPROJECT namespace if does not exist
  if (!window.MYPROJECT) {
   window.MYPROJECT = {};
  }
 
  // Create MYPROJECT.errorHandler namespace if does not exist
  if (!window.MYPROJECT.errorHandler) {
   window.MYPROJECT.errorHandler =  (function () {
 
    var config, init, logError;                             
 
    config = {
     timeout: '5000',
     errorLogURL: '/ApplicationName/LogError'   //default URL 
    };
 
    /**
     * private function to register the logError handler
     */
    init = function (errorLogURL) {
     window.onerror = logError;                                           //the onerror event on windows invoke the logerror function
     config.errorLogURL = errorLogURL || config.errorLogURL;   // if not defined use default URL
    };
 
    /**
     * private function to log error
     */
    logError = function (msg, url, lineNo) {
     
    //makes an ajax post to the server using the jQuery library
     jQuery.ajax({
      url: config.errorLogURL,                                  //URL for the AJAX POST 
      type: 'POST',
      data: {'msg' : msg, 'url' : url, 'lineNo' : lineNo},  //log msg, the URL of the .js file containing the error, and the line number of the error
      timeout: config.timeout
     });
 
     return false;
    };
 
            //public methods that can be invoked from outside 
    return { init: init, logError: logError };
   
   }());
  }
}());


The above code can be used as follows.

STEP1: Initialize when the document loads

jQuery(document).ready(function () {
 'use strict';
 MYPROJECT.ajaxErrorHandler.init('/myapp/logError');
});

STEP2: Log the error where required

if(someErrorCondition) {
    MYPROJECT.errorHandler.logError('Error message is .... ', 'test.js','36');
}

or

try {
    //some logic
} catch (ex) {
       MYPROJECT.errorHandler.logError(ex.message, ex.fileName, ex.lineNumber);
}


On the serverside, you could write a Java Servlet to recieve and process this ajax request by writing to the serevr log using a library like log4j.

package somepkg;
 
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class ErrorLoggingServlet extends HttpServlet {

 private static Logger logger = Logger.getLogger(ErrorLoggingServlet.class);

  public void service(HttpServletRequest req, HttpServletResponse res)
             throws ServletException, IOException {
  
        //extract the request parameters  
  String msg = req.getParameter("msg");
  String file = req.getParameter("url");
  String lineNo = req.getParameter("lineNo");

   // extract the user-agent, ie browser.
   String userAgent = req.getHeader("user-agent");
        
  //log the client-side error to the server side log file
  logger.error(String.format("JSError: %s \n%s(Line:%s)\nBrowser: %s",
    trim(msg), trim(file), trim(lineNo), trim(userAgent)));
 }
 
 /**
   * Trim the input parameters before logging to avoid unfiltered input 
  * from the client side filling up the log files.
  */
  private String trim(String in) {
  return (in != null) ? in.substring(0, 100) : "";
  }
}


Q. How would you go about making an AJAX call using a JavaScript framework like jQuery to retrieve json data?
A. The sample code below uses 3 files


  • test3.html -- The html file with the button to click
  • test3.js -- The JavaScript file that makes use of the jQuery framework to make the AJAX call.
  • test3.json -- The json data file containing data to be retrieved via AJAX requests.

Firstly, the test3.html


<!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="jquery-1.4.2.js">
</script>
<script language="javascript" type="text/javascript" src="test3.js">
</script>


<title>Insert title here</title>
</head>
<body>
  <form>  
Click the button to fetch json data:  
     <input id="go" type="button" value="go"/>  
  </form>

</body>
</html>


Note that jquery-1.4.2.js is jQuery library.


Next, the the test3.json file

{"data" :
 { 
  "topics": 
          [
              "Java",
     "JEE",
     "JavaScript",
     "Unix"
          ]
 }
} 


Finalyy, the test3.js


$(document).ready(function(){
  $('input#go').click(function() {
 $.ajax({
  type: "GET",
  url: "http://localhost:8080/webdav/test3.json",
     beforeSend: function(xhr){
          if (xhr.overrideMimeType)
         {
           xhr.overrideMimeType("application/json");
         }
       },
   dataType: "JSON",
 

  success: function(data) {
     console.log(data);
           var obj = jQuery.parseJSON(data);
     alert(obj.data.topics);
  } 
    
  
 });
  
  });
});


To run the above sample files, you need an HTTP Web server. I downloaded and installed the tomcat server (version 5), and copied the above 3 files to the sample webapp that comes with the installation. The copied folder is <tomcat-home>/webapps/webdav. The "webdav" is the web appplication context. Copy the 3 files to "webdav". Start the tomcat server via <tomcat-home>/bin/startup.bat (or startup.sh for Unix). You can now open up a browser like Firefox and enter the URL as http://localhost:8080/webdav/test3.html invoke test3.html. Click on the button, and you will the json data getting alerted.


You could also check the webconsole in Firefox via Tools --> Web Developer --> Web Console (available in version 4.0 onwards). Also, download the Firebug plugin, and open the plugin. Go to the "Net" and then "XHR" tab in the plugin to view the AJAX requests being made. Also, feel free to get more familarized with the firebug, which is very handy for debugging your Web application on client side.



More JavaScript Q&A

Labels:

Jan 24, 2012

UNIX Interview questions and answers

Unix for software developers

1.Top 17 Unix commands Java developers use frequently 2.History commands 3.Shell scripting 4. Reading from a file
5.Purging older files 6.Splitting and archiving files 7.Emulator, SSH client 8.Unix commands for developers 9.Unix basic interview Q&A

In Core Java Career Essentials book, I had covered some of the core UNIX commands that are useful to Java developers with practical and real life examples. This blog expands on it with some handy UNIX features to complement the book.

Q. Where would you use the control operators like ";", "&&", and "||" in UNIX?
A. These control operators are used to combine different commands in a single line. There is a difference between the characters in a sense how the subsequent commands are executed. For example,

The following commands use a ";" to separate commands. This means both the commands will be executed regardless of the first command is successful (i.e. exit code of 0) or not (i.e. exit code other than 0);

$ cd Temp; echo $(pwd)

You could get an output shown below if there is folder named Temp.

/c/Temp

If the folder named Temp is not present, you will get an error and the current directory printed.

sh: cd: Temp: No such file or directory
/c


So, what if you want to only print the current directory if the first change directory command is successful? This is where the "&&" operator comes in handy.

$ cd Temp && echo $(pwd)

In the above example, the echo command will only be excuted if the change directory command is successful. If not successful, only an error will be thrown, and the current directory will not be printed. There are situations where
you might want to do the reverse. That is, execute the second command only if the first command fails. For example, make a "Temp" directory only if the change directory fails. This where the "||" operator comes in handy.

$ cd temp ||  mkdir temp && cd temp  && echo $(pwd)

If, temp directory is not found, make a new directory named temp, and if make direcory is successful, change to that directory and echo the current directory.


Q. What do you uderstand by 2>&1 in UNIX?
A. In UNIX you have STDIN, which is denoted by number 0, STDOUT, which is denoted by 1, and STDERR, which is denoted by 2. So, the above line means, the error messages go to STDERR, which is redirected to STDOUT. So, the error messages go to where ever the STDOUT goes to. For example, The following command creates a multiple directories for a maven based Java project. if the the directory creation is successful, change directory to "project" and print the directory tree structure. The STDOUT and STDERR are directed to the file named maven-project.log under the project folder.

$ mkdir -p project/{src/{main/{java,resources},test/{java,resources}}} && cd project ; find . -type  d -print  > maven-project.log



The output will be something like

.
./src
./src/main
./src/main/java
./src/main/resources
./src/test
./src/test/java
./src/test/resources


Q. What is /dev/null?
A. It is a blackhole. For example, in the earlier example, if you want to ignore error like "sh: cd: Temp: No such file or directory" being printed, you can redirect your output to /dev/null. For example

$ cd temp > /dev/null 2>&1 && echo $(pwd)

will fail silently and nothing will be printed if there is no "temp" folder. The message has gone into the blackhole. If there is a "temp" folder, the present working directory (i.e. pwd) will be printed out.

Q. How would you go about the following scenario -- You had to move to another directory temporarily to look at a file, and then move back to the directory where you were?
A. One way is to start with "/c/Temp" folder

$ cd ../projects/JMeter
$ cd ../../Temp


The better way is to use the pushd and popd commands. These commands make use of a "stack" data structure using the "Last In First Out" approach.

changes to the /c/Projects/JMeter folder and prints the stack

$ pushd ../projects/JMeter

The stack is printed as shown below.

/c/projects/JMeter /c/Temp

The /c/projects/JMeter will be popped out of the stack and the directory will change back to /c/Temp

$ popd


If you want pushd to not print the stack, you could direct the output to the black hole /dev/null as shown below.

$ pushd ../projects/JMeter > /dev/null

The above is a trivial example, but in real life, you may want to navigate between more number of directories and this stack based approach will come in very handy without having to use the "cd" command. Also, very useful in UNIX scripts. Use it astutely without having to build up a gigantic directory stack full of useless directories.


Q. In UNIX, only nine command line arguments can be accessed using positional parameters. How would you go about having access to more than 9 argumnets?
A. Using the shift command. For example, in unix, when you run a command like

$ sh test-bash.sh file1 file2 file3 file4 file5 file6 file7 file8 file9, file10, fil11

The ${0} is test-bash.sh, and ${1} is file1, ${2} file2 and so on till ${9}, which is file9. In the program, if you want to access file10 after processing file1 to file9, you need to use the "shift" command.

$ shift

All it does is move all the command line arguments to the left by 1 position. Which means the file1 will be moved out, and file2 becomes ${1} and file10 becomes ${2}. If you shift it agian, the file3 becomes ${1} and file11 becomes ${9}. In a nutshell


${#} - Total number of arguments
${0} - Command or the script name
${1},${2}, ${3} - First, second and third args respectively.
${*} - All the command line arguments starting from $1.
${@} - Same as ${*} except when it is quoted "${@}" will pass the positional parameters unevaluated. For example, echo "${@}" will print

echo "$1" "$2" ...



Q. How will you go about writing a UNIX shell script, that reads one or more data files like the one shown below and perform a particular task like logging the information in the file or making database calls to patch some data?


The test-data.txt

Server Name:Database Name:username: password
Line2-file-name1.sql
Line2-file-name2.sql
Line2-file-name3.sql


The usage of the script will be something like

$ sh test-bash.sh test-data.txt test-data2.txt test-data3.txt


A. The sample script below will be predominantly making use of the commands discussed above. If not clear, try to read and understand the above Q&As. The best way to learn is to try it out yourself. The lines starting with "#" are comments. If you do not have a UNIX environment, download a windows UNIX emularor like MSYS or CYGWIN to run it on your WINTEL platform.

The test-bash.sh.

#!/bin/bash

# usage is -->  sh Temp/test-bash.sh Temp/test-data.txt
# ${0} is  Temp/test-bash.sh 
# ${1} is  Temp/test-data.txt

echo No of arguments:  ${#}
echo Arguments are: ${*}
echo Arguments are: ${@}

#usage sub function that gets invoked by the main function.
#Echo the usage pattern and exit the script.   
usage () {
 echo Usage : $(basename ${0}) file
 exit 1
}


#log sub function that gets invoked by the main function.
log () {
 echo ${@}
 echo ${@} >> ${LOGFILE}
}


#-r means FILE exists and is readable. 
#If the file does not exists or not readable, invoke the "usage" sub routine  to print the usage
[[ -r ${1} ]] || usage


#dirname prints the directory & basename prints the file-name
echo script directory name is: $(dirname ${0})   #
echo script-name is:   $(basename ${0}) 
echo data directory name is: $(dirname ${1})
echo data-file-name is:   $(basename ${1}) 

CMDFILE=$(basename ${1})

#this will be test-data.txt.log
LOGFILE=$(basename ${1}).log

#  take the first line in the data file and
#  translate ':" to ' ' (i.e. translate colon to empty space) 
COMMAND=($(head -1 ${1} | tr ':'  ' '))

#log the first line values in the data file 
#separate with a comma
log ${COMMAND[0]},${COMMAND[1] },${COMMAND[2]}


pushd $(dirname ${1}) > /dev/null

#log an empty line
log

#log start timestamp
log BEGIN $(date)


for SQLFILE in $(sed -n '2,$p' ${CMDFILE}); do
 log  ${SQLFILE}
 # in real life execute the sql commands using an interactive SQL command. For example
 # isql -S ${COMMAND[0]} -D ${COMMAND[1]} -U ${COMMAND[2]} -P ${COMMAND[3]} < ${SQLFILE} > ${LOGFILE} 2>&1
done

#log end time stamp
log END $(date)

popd > /dev/null

# if more data files are supplied as commandline arguments shift so that second file becomes ${1} and so on
shift

#If more filenames are supplied in the commandline arguments, repeat the script for the successive filenames.
[[ ${@} ]] && ${0} ${@}



The output for


$ sh test-bash.sh test-data.txt

will be


No of arguments: 1
Arguments are: test-data.txt
Arguments are: test-data.txt
script directory name is: .
script-name is: test-bash.sh
data directory name is: .
data-file-name is: test-data.txt
Server,Name,Database

BEGIN Tue Jan 24 12:57:16 AUSEDT 2012
Line2-file-name1.sql
Line2-file-name2.sql
Line2-file-name3.sql
END Tue Jan 24 12:57:16 AUSEDT 2012

Labels:

Jan 11, 2012

JavaScript Interview Questions and Answers: Function.call, Function.apply, and Callback functions



Q. What are the different ways to invoke a function? What would the implicit reference "this" refer to?
A. The functions can be invoked via one of the following 5 ways

  1. function_name(param1, param2, etc); --> "this" refers to global object like window.
  2. obj1.function_name(param1,param2,etc);  --> "this" refers to obj1.
  3. The constructor.
  4. function_name.call(objRef, param1);    //remember that the functions in JavaScript is like an object and it has it's own methods like toString(..), call(...), apply(...), etc.
  5. function_name.apply(objRef, params[parama1,param2, etc]);


So, why use  function_name.call(...) or function_name.apply( ... ) as opposed to just function_name( ... )? Let's look at this with some examples.
var x = 1;           //global variable x;

var obj1 = {x:3};   //obj1 variable x
var obj2 = {x:9};   //obj2 variable x

function function_name(message) {
   alert(message + this.x) ;
}


function_name("The number is ");              //alerts the global x --> The number is 1

//the first argument is the obj reference on which to invoke the function, and the
//the second argument is the argument to the function call
function_name.call(obj1, "The number is ");   //alerts the obj1's x --> The number is 3
function_name.call(obj2, "The number is ");   //alerts the obj2's x --> The number is 5



//the first argument is the obj reference on which to invoke the function, and
//the second argument is the argument to the function call as an array
function_name.apply(obj1, ["The number is "]);   //alerts the obj1's x --> The number is 3
function_name.apply(obj2, ["The number is "]);   //alerts the obj2's x --> The number is 5


The purpose is of call and apply methods are  to invoke the function for any object without being bound to an instance of the this object. In the above example, the this object is the global object with the x value of 1.   In a function called directly without an explicit owner object, like function_name(), causes the value of this to be the default object (window in the browser). The call and apply methods allow you to pass your own object to be used as the "this" reference. In the above example, the obj1 and obj2 were used as "this" reference.



Q. What will be the alerted message for buttons 1-5 shown below?

The test.html stored under js_tutorial/html


<!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">

<title>Insert title here</title>
</head>
<body>
    <form id="someform">
       <input id="btn1" type="button" value="click-me1"/>  
       <input id="btn2" type="button" value="click-me2"/> 
       <input id="btn3" type="button" value="click-me3" onclick="buttonClicked()"/>  
       <input id="btn4" type="button" value="click-me4"/>  
       <input id="btn5" type="button" value="click-me5"/>  
    </form>
    
    <script language="javascript" type="text/javascript" src="../js/test.js">
    </script>
    
</body>
</html>


The test.js stored under js_tutorial/js.

function buttonClicked(){  
    var text = (this === window) ? 'window' : this.id;  
    alert( text );  
}  

var button1 = document.getElementById('btn1');  
var button2 = document.getElementById('btn2');  
var button4 = document.getElementById('btn4');  
var button5 = document.getElementById('btn5');  

button1.onclick = this.buttonClicked; //or just  button1.onclick = buttonClicked; 
button2.onclick = function(){   
 buttonClicked();   
};  

button4.onclick =  function(){   
 buttonClicked.call(button4);   
};  

button5.onclick =  function(){   
 buttonClicked.apply(button5);   
}; 


A. The "this" object passed to the buttonClicked function are as follows:

click-me1 --> btn1 ("btn1" because it's a method invocation and this will be assigned the owner object - the button input element)
click-me2 --> window (This is the same thing as when we assign the event handler directly in the element's tag as in click-me3 button)
click-me3 --> window (global object)
click-me4 --> btn4
click-me5 --> btn5

When defining event handlers via frameworks like jQuery, the library will take care of overriding the value of "this" reference to ensure that it contains a reference to the source of the event element. For example,


$('#btn1').click( function() {  
     var text = (this === window) ? 'window' : this.id;  //// jQuery ensures 'this' will be the btn1
    alert( text );  
});  


The jQuery makes use of apply( ) and call( ) method calls to achieve this.


Q. What will be the output for the following code snippet?

<!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">

<title>Insert title here</title>
</head>
<body>
    <form id="someform">
       <input id="btn1" type="button" value="click-me1" onclick="test()"/>  
    </form>
    
    <script language="javascript" type="text/javascript" src="../js/test2.js">
    </script>
    
</body>
</html>


the test2.js file.

var myobj1 = {  
  x:9, 
  myfunction:function(){
 
    if(this === window) 
     alert("x is not Defined");
 else if (this === myobj1)
     alert(this.x);
 else 
  alert("Error!");
  }
}


function test(){
 setTimeout(myobj1.myfunction, 1000);
}



A. The output in the alert will be "x is not defined". This is because the "this" will be referring to the default global object -- window. The above code can be fixed by replacing the test() function as shown below.

function test(){
 setTimeout(function(){
  myobj1.myfunction()}, 
 1000); 
}


Note: The setTimeout(..,..) method alerts only after 1 second of clicking the button.

Q. What is a callback function? Why would you need callback functions?
A. As mentioned earlier, the functions in JavaScript are actually objects. For example,

var functionAdd = new Function("arg1", "arg2", "return arg1 * arg2;");
functionAdd(5,9);  // returns 14
functionAdd(2,3);  // returns 5


So, the functions can be passed as arguments to other functions and invoked from other functions. For example,

function functionAdd(arg1, arg2, callback) {
  var result = arg1 + arg2 
  // Since we're done, let's call the callback function and pass the result
  callback(result);
}

 
// call the function
functionAdd(5, 15, function(result) {
    // this anonymous function will run when the callback is called
 console.log("callback called! " + result);
}); 


Why invoke the callback function when the functionAdd(..) could have executed the results? Client-side is predominantly asynchronous with following types of events.

UI Events like mouse click, on focus, value change, etc. These events are asynchronous because you don't know when a user is going to click on a button. So, callback functions need to be invoked when a button is clicked. For example JavaScript frameworks like jQuery quite often uses callback functions. Whether handling an event, iterating a collection of nodes, animating an image, or applying a dynamic filter, callbacks are used to invoke your custom code at the appropriate time.

The test.js.

$(document).ready(function(){
  $("button").click(function(){
    $("p").hide(2000,function(){
    console.log("Inside the callback function...");
   //called 2 seconds after the paragraph is hidden 
      alert("The paragraph is now hidden");
    });
  });
});


The test.html

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="test.js"></script>

</head>
<body>
<button>Hide</button>
<p>The praragraph to hide when a button is clicked.</p>
</body>
</html> 


Timer functions like setTimeout(function, delay), setInterval(function, delay), etc will delay the execution of a function. For example, you might want to disable a form button after it's been clicked to prevent double form submission, but then re-enable it again after a few seconds. The clearTimeout() function then allows you to cancel the callback from occuring if some other action is done which means the timeout is no longer required.
Another reason why these timers are useful is for some repetitive tasks some milliseconds apartment. The reason why the timers are used instead of a simply while (true) { ... } loop is because Javascript is a single-threaded language. So if you tie up the interpreter by executing one piece of code over and over, nothing else in the browser gets a chance to run. So, these timers allow other queued up events or functions to be executed.

Invoke myObj1.myObj1.myMethod() after 1 second.

var myObj1 = {
     myVar:12, 
  myMethod:function(){
      alert(this.x || "Not defined") ; // "Not defined" is the default if x is not defined
    }
}


setTimeout(function(){myObj1.myMethod()}, 1000);




Ajax calls are made asynchronously and when a response is received from the server, a callback method is invoked to process the response. The Ajax calls do have the following states

AJAX states:

0: The request is uninitialized (before you've called open()).
1: The request is set up, but not sent (before you've called send()).
2: The request was sent and is in process (you can usually get content headers from the response at this point).
3: The request is in process; often some partial data is available from the response, but the server isn't finished with its response.
4: The response is complete; you can get the server's response and use it.

So, you want the callback function to be invoked when the state == 4. Let's look at an example.

Here is the test2.html

<!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="ajax.js">
</script>

<title>Insert title here</title>
</head>
<body>
</body>
</html>


The ajax.js.

function processAjaxRequest(url, callback) {
    var httpRequest; // create our XMLHttpRequest object
    if (window.XMLHttpRequest) {
     //For most browsers
        httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        //For IE
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }

    //onreadystatechange event registers an anonymous (i.e. no name) function
    httpRequest.onreadystatechange = function() {
       // this is called on every state change
       if (httpRequest.readyState === 4) {
            callback.call(httpRequest.responseXML);   // call the callback function
       }
    };
    httpRequest.open('GET', url);
    httpRequest.send();
}


processAjaxRequest ("http://localhost:8000/simple", function() {
    console.log("Executing callaback function....");
    console.log("1.This will be printed when the ajax response is complete. ");   //LINE A
});

console.log("2. This will be printed before the above console.log in LINE A.");   //LINE B


Note: If you use FireFox, you can vie the console via Tools --> Web Developer --> Web Console. When you run the above example, check the web console output.

Now, for the purpse of learning JavaScript, Ajax, etc, you can create your own HTTP server with a quick and dirty approach as shown below. The Java 6, has a built in non-public API for HTTP. This approach should not be used in real life.

The Java HTTP Server

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;



public class SimpleJavaHTTPServer {

 public static void main(String[] args) throws Exception {
  HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
  server.createContext("/simple", new MyHandler());
  server.setExecutor(null); // creates a default executor
  server.start();
 }

 static class MyHandler implements HttpHandler {
  public void handle(HttpExchange t) throws IOException {
   String response = "<ajax-xml>some text</ajax-xml>";
   t.sendResponseHeaders(200, response.length());
   OutputStream os = t.getResponseBody();
   os.write(response.getBytes());
   os.close();
  }
 }
}


The LINE B will be printed before LINEA.

Note: If you run the above Java code within Java 6 or later, you will get an ajax response of <ajax-xml>some text</ajax-xml> when you invoke http://localhost:8000/simple. You may get a "restricted API" in eclipse IDE, you could overcome this by removing and adding the rt.jar via the build path or you could try the following from the preferences menu go into Java --> Compiler --> Errors/Warnings --> Depricated and Restricted API and change the "forbidden reference" from "Error" to "Warning".



More JavaScript Q&A

Labels:

JavaScript Interview Questions and Answers: Closure



We earlier saw that JavaScript functions are like objects, and can be passed as arguments from one function to another, can be assigned to a variable, etc.


Q. What do you understand by the term closure in JavaScript?
A. Whenever you have a function within a function, a closure is used. A closure is like local variables for functions. Let's look at an example.


var calculate = function(x) {     //outer function    
     var myconst = 2; 
     myconst++; //myconst is now 3
     return function(y) {           //inner function
         return x + y + myconst;    // has visibility to parent variable 'myconst'
     }; 
        
}  

//closure 1: each function call has its own closure
var plus5 = calculate(5);       // plus5 is now a closure to the inner function, 
                                // and has access to the outer function's values
                                // when function call exits myconst = 3 and x = 5 

console.log(plus5(3));          // returns 11  i.e. x=5, y=3, myconst=3 


//closure 2: each function call has its own closure
var plus7 = calculate(7);       // plus7 is now a closure to the inner function, 
                                // and has access to the outer function's values
                                // when function call exits const = 3 and x = 7 



console.log(plus7(4));          // returns 14  i.e. x=7, y=4, const=3 



In general, when you exit out of a function, all the local variables (e.g.myconst and x) go out of scope. As per the above example, you could think that a closure is created on entry to the outer function, and the local variables are added to the closure. The closure is stored to the variable like plus5, plus7, etc and invoked by passing the value for "y". Each function call will have its own closure (e.g. plus5 and plus7)


So, a closure means the local variables of the outer function is kept alive after the function has returned.


Example 2:

function count() {
    var num = 0;    //local variable that ends up within enclosure
    var display = function() {  // the variable "display" is also part of the closure
       console.log(num++);  
    }
    
    num++; //the num is 1
    
    
    return display;
}


var  increment = count(); // num is 1

increment();    //Can be assigned to a button.
                //every time invoked displays number starting from 2, and incrementing it by 1 as in 2,3,4,etc.



In the above example, the variable "display" is also inside the closure and can be accessed by another function that might be declared inside count() or it could be accessed recursively within the "display" function itself.

Q. What will be the out put of the following JavaScript when you click on the "click-me" button that invokes the function testList()?

<form id="evaluate1">
    <input type="button" value="click-me"  onclick="testList()"/>  
</form>

function listCars (list) {
   var listOfFns = [];
   //construct and store functions
   for(var i=0; i<list.length; i++) {
      listOfFns.push(function() {console.log("The car is: "  + list[i])});
   }

   return listOfFns;
}


function testList() {
    var listOfFns = listCars(["Toyota", "Honda", "Ford", "Mazda"]);   //Line A
    //invoke the functions by looping through             
     for(var i=0; i<listOfFns.length; i++) {                          //Line B 
        listOfFns[i]();
     }

}



A: The output will be "The car is: undefined". This is because when the closure is created in "Line A" the the value of the variable "i" in function listCars(…) is 4, which is the exit condition for the for loop. Now in Line B, when you try to execute the inner function

function() {
   console.log("The car is: "  + list[i]);
}


Since the value of i in the closure is 4, the list only has 4 elements with indices 0,1,2, and 3, the index 4 is undefined. That list[4] is not defined. This is a general gotcha when working with closure and arrays.



Points to remember:

  • Closures are created every time you create a function in a function.
  • Closures give you access to variables that are defined in the parent function, and all of its parents.
  • Closures will help you keep your code clean and easy without having to use the global variables.


//outer function
function createTimer() {
       // inner function invoked from the outer function using closure
       function alertTimerId() {
            // the timerId is a local variable from the outer function, which is in the closure
            alert("The timer id is " + timerId);
       }
     
       //invoke the inner function from the outer.
       var timerId = window.setTimeout(alertTimerId, 1000); // alerts after 1000 ms or 1 second.
}
     
createTimer();




The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

setTimeout(code,millisec,lang)




code (Required) -- A reference to the function or the code to be executed
millisec (Required) -- The number of milliseconds to wait before executing the code
lang (Optional) -- The scripting language: JScript | VBScript | JavaScript



Q. What is a "module pattern"?
A. The module pattern emulates familiar OO concepts of private and public methods and attributes. It does so by utilizing closures to "hide" elements from the global scope. The public behavior is achieved by returning the private members from your object. Public functions can access the private members.

Global variables are evil, and Douglas Crockford has been teaching a useful singleton pattern for avoiding global variables. The "module pattern" creates an anonymous function, and executes it immediately. All of the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application.

(function () {
 // all vars and functions are in this scope only
 // still maintains access to all globals
}());




So there is a difference between function declartion and function expression. The identifier (e.g print) is optional for the function expression. Here is an example of function expression.
 

//function declaration
function print(msg){
   alert(msg);
 }


 
//function expression
(function (msg){
   alert(msg);
 }
)('Hello World');


Note that the () around the anonymous function is required by the language, since statements that begin with the token function are always considered to be function declarations. Including () creates a function expression instead. Here is an example

var  myProject = {};   //some namespace



myProject.myModule = (function () {



 //"private" variables:

 var myPrivateVar = "myPrivateVar can be accessed only from within myProject.myModule.";



 //"private" method:

 var myPrivateMethod = function () {

  console.log("myPrivateMethod can be accessed only from within myProject.myModule");

 }



 return  {

  myPublicProperty: "myPublicProperty is accessible as myProject.myModule.myPublicProperty.",

  myPublicMethod: function () {

   console.log("myPublicMethod is accessible as myProject.myModule.myPublicMethod.");



   //Within myProject.myModule, I can access "private" vars and methods:

   console.log(myPrivateVar);

   myPrivateMethod();



   //access public members using "this" as the native scope of myPublicMethod is myProject.

   console.log(this.myPublicProperty);

  }

 };



}());





function test() {

    alert(myProject.myModule.myPublicProperty); //defined -- accessing public property

    myProject.myModule.myPublicMethod();        //defined -- accessing public method

    alert(myProject.myModule.myPrivateVar);     //undefined -- accessing private property -- NOT OKAY

    myProject.myModule.myPrivateMethod();       //myProject.myModule.myPrivateMethod is not a function -- accessing private method -- NOT OKAY

}

Pros and Cons
Pros:
  • Easy to pick up for software engineers, as this emulates a familiar pattern
  • Clean encapsulated code
  • Private methods and attributes
Cons:
  • Dependent on ordering
  • Accessing public methods requires repeating the parent object name
  • Lack of full support for private members


The Revealing Module Pattern is an extension of the Module Pattern, the main difference being that all methods and attributes are declared as private and optionally exposed in the return of the object. In the process of exposing the methods/attributes we additionally have the option of providing a different name for the exposed reference.


var  myProject = {};        //some namespace

myProject.myObject = (function() {
    var myPrivateVar = "private";
    var myPrivateFunction = function() {
     console.log("private function is called");
        return myPrivateVar;
    }
 
    return {
        publicFunctionName: myPrivateFunction
    }
}())


function test() {
    myProject.myObject.publicFunctionName();       //defined -- accessing public method
    myProject.myObject.myPrivateFunction();        // myProject.myObject.myPrivateFunction is not a function -- NOT OKAY
}



Pros and Cons

Pros:

  • Easier to read structure
  • All methods/attributes are referenced in the same way
  • Ability to expose members with a different name

Cons:

  • Lack of full support for private members


You can learn more about the JavaScript design patterns at Essential JavaScript Design Patterns For Beginners, Volume 1.-- Addy Osmani.


More JavaScript Q&A

Labels:

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.

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.

function Person(name, status) {
    this.name = name;
    this.status = status;
    //add a method by associating a function to variable isActive variable.
    this.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.

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,

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.

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.

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

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:


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

    Use:

    <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

    $('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

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

    Use:

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


    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


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.


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( )) ;
 
 
  • 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.

  • Favor [ ] to declare an array as opposed to an array object with new Array( ). For example,
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


//okay
var x = 5;
var y = 6;
var z = 9;

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



More JavaScript Q&A

Labels:

Jan 9, 2012

JavaScript Interview Questions and Answers: Overview



More JavaScript Q&A




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.

    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.

    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).

    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. 
           
    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.

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

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. 

    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.
    <!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.
    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. 
<!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.


    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.


    var calculate = function(x) {    
         var myconst = 2; 
         return function(y) { 
             return x + y + myconst;    // has visibility to parent variable 'x' and myconst
         }; 
    }  
    
    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 onClick, etc.

  • 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
     
    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.
<!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>

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.
<!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>

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"
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());
   
}



Note: I am new to JavaScript, so feel free to point out any errors.

More JavaScript Q&A

Labels: