Tuesday, 13 August 2013

Interview question on Javascript

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.

<input type="text" name="date" />
Say an input field with the name “date” had to be validated at runtime:

document.getElementsByName("date")[0].
                   addEventListener("change", validateDate, false);

function validateDate(){
// Do something when the content of the 'input' element with the name
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.
Java script
Jscript
It is developed by Netscape communications
It is developed by Microsoft. It runs in Internet Explorer. It has the access to different objects that are exposed by the browser. ActiveXObject is one such object
It is a scripting language. Netscape navigator interprets javascript embedded into web pages.
It is a scripting language
It is used to for developing web applications
It is designed to create active online content
It is not dependent on Sun Microsystem’s java language.
ActiveX controls, java programs, etc can be linked and automated in the web pages using Jscript

client side javascript vs server side javascript
Client side java script
Server side javascript
It comprises the basic language and predefined objects which are relevant to running java script in a browser
Server side java script slso resembles like client side java script.
It is embedded directly by in the HTML pages.
The server side java scripts are deployed only after compilation
This script is interpreted by the browser at run time
It has relevant java script which is to run in a server.
Enables web pages on browsers to run active online content
It is javascript that enables back-end access to databases, file systems, and servers

Where are cookies actually stored on the hard disk?
This depends on the user's browser and OS.

In the case of Netscape on Windows OS, its stored in cookies.txt
In Internet Explorer, each cookie is stored in a file and has is named as username@website.txt.

The path is :
c:\Program Files\Netscape\Users\username\cookies.txt
The Internet Explorer stores the cookies on a file by name username@website.txt is
c:\Windows\Cookies\username@Website.txt 

What is the difference between a web-garden and a web-farm?

The term ‘Web Farm’ indicates a business that performs Web site hosting on multiple servers.
The term ‘Web Garden’ means a multi-processor machine.

Difference between SessionState and ViewState

Sessionstate
Viewstate
It is a state of a page within a browser wherein the values of controls persist when post back operation is done.
SessionState is the data of a user session and is maintained on the server side. This data available until user closes the browser or session time-outs.

How to Accessing Elements using javascript?

Following are some of the functions with which the elements can be retrieved:
getElementById()
getElementByName()
getElementByValue()
getElementByTag()

What is the difference between undefined value and null value?

Undefined value: A value that is not defined and has no keyword is known as undefined value. For example in the declaration, int number; the number has undefined value.
Null value: A value that is explicitly specified by the key word ‘null’ is known as null value. For example in the declaration, String str=null; the str has a null value. The keyword ‘null’ is used here.

How to set the cursor to wait in JavaScript?

<html>
<div style="width: 100px; height: 100px; background: yellow; cursor: wait">
A moue over this yellow patch will show you the wait cursor.
</div>
</html>

Difference between client side java script and server side java script

Client side java script
Server side javascript
It comprises the basic language and predefined objects which are relevant to running java script in a browser
Server side java script slso resembles like client side java script.
It is embedded directly by in the HTML pages.
The server side java scripts are deployed only after compilation
This script is interpreted by the browser at run time
It has relevant java script which is to run in a server.
Enables web pages on browsers to run active online content
It is javascript that enables back-end access to databases, file systems, and servers

difference between Java script and Jscript

Java script
Jscript
It is developed by Netscape communications
It is developed by Microsoft. It runs in Internet Explorer. It has the access to different objects that are exposed by the browser. ActiveXObject is one such object
It is a scripting language. Netscape navigator interprets javascript embedded into web pages.
It is a scripting language
It is used to for developing web applications
It is designed to create active online content
It is not dependent on Sun Microsystem’s java language.
ActiveX controls, java programs, etc can be linked and automated in the web pages using Jscript

Monday, 12 August 2013

External Javascript

external javascript
open new document and write the java script code(functions)
 function validate(login form)
 {
   Same code from previous example
 }
·         same the above document with any name .js as the extension Exampe: check.js
·         to include the external javascript file in the html document we ned to use src attribute of <script> tag.
Syntax: <script type=”text/javascript” src=”chack.js”>
</script>
Note:


It is always recommenteded to write external javascript code because the same code can be used in multiple html documents

JAVA SCRIPT EVENTS

Events can be detected by the browser.
·         Events are generated when the user performs a particular action.
·         Events are generally associated with the functions so that the code(logic) present in the function will be executed when the specified event occurs.
·         The various java script events are:
1.       onclick:
2.       ondblckick
3.       onkeydown
4.       onkeyup
5.       onkeypress
6.       onmousedown
7.       onmouseup
8.       onousemove
9.       onmouseover
10.   onmouseout
11.   onfocus
12.   onblur
13.   onsubmit
14.   onreset
15.   onchange
16.   onerror
onload

1. onclick
     This event is generated when the user clicks on a button
2. ondblclick
      this event is generated when the user double clicks on
3. onkeydown
      this event is generated when the user presses a key and the key is not yet released
4. onkeyup
     this event is generated when the user releases a key
5. onkeypress
       this event is generated when a key pressed and released.
6. onmousedown
       this event is generated when the user presses the mouse button and it is not released.
7. onmouseup
     this event is generated when the user releases the mouse button
8. onmousemove
     this event is generated when the mouse pointer location is changed.
9. onmouseover
       this event is generated when the mouse pointer is placed on top of a text(or) image
10. onmouseout
       this event is generatd when the mouse pointer is removed from a top of a text (or) image.
11. onfocus
       this event is generated when an input element contains focus (i.e having control)
12. onblur
       this event is generated when the focus is lost
13. onsubmit
        this event is generated when the submit button is clicked
14: onreset
        this event is generated when the reset button is clicked
15. onchange
       when there is a change in the values of the input elemntes
16. onerror
      when an error occurs in th edocument.
17. onload
       this event is generated when a docuement is loaded on to the browser.
18. onunload
      this event is generated when the document is unloaded from the browser.
19. onresize
       this event is generated when there is a change in the size of the window (or) Frame.

<html>
 <head>
  <script type="text/javascript">
   function change()
   {
     var name=myform.user.value;
     var color=myform.col.value;
     document.bgcolor=color;
     alert(name+"has changed the bg color to"+color);
   }
  </script>
 </head>
<body>
 <form name="myform">
  username<input type="text" name="user"/><br/>
  Color<input type="text" name="Id"/> <br/>
  <input type="button" value="change"

onclick=change();
 </form>
</body>

</html>

//a progr is based on all on submit events
<html>
 <head>
 <title> Login page</title>
  <script type="text/javascript">
  function validate(loginform)
  {
    var user=loginform.uname.value;
    var pass=loginform.prod.value;
    if(user.length==0)
    {
     alert("enter your name");
     loginform.uname.focus();
     return false;
    }
    if(pass.length==0)
    {
     alert("enter your password");
     loginform.pwd.focus():
     return false;
    }
   }
  </script>
 </head>
 <body>
 <center>
 <h1>login page</h1>
  <form name="loginform"
   onsubmit="return validate<this)">
   username<input type="text" name="uname"/><br/>
   password<input type="passowrd" name="pwd"/> 

<br/>
  <input type="submit" value="login" />
 </form>
 </center>
</body>

</html>


output

we can write the javascript code within the html document(internal javascript code) or external to the html document(External javascript code)

java script Objects

java script Objects

Objects:
Javascript is a object oriented language which allows the user to use predefined object (or) create user defined objects.
·         Object is a kind of data that contains properties and methods.
·         Properties are used to hold the values that provide the information about the object
·         Methods are the actions that are performed on the objects

There are two ways to create objects in Javascripts

1. Direct instance
2. using functions( constructors)
1. using Direct instance:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object();   // Create the object
    book.subject = "html"; // Assign properties to the object
    book.author  = "Ram";
</script>
</head>
<body>
<script type="text/javascript">
   document.write("Book name is : " + book.subject + "<br>");
   document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>

2. using constructors

<!object constructor>
<html>
<body>

<script>
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
document.write(firstname + " is " + age + " years old.");
}

myFather=new person("vijay","kumar",50,"blue");
//document.write(myFather.firstname + " is " + myFather.age + " years old.");

</script>

</body>

<!-- http://improvejavascript.blogspot.in/-->
</html>


Types of Objects:

  • There are two types of objects are available
  • 1. User Defined Objects 
  • 2. Predefined Objects


In JavaScript almost everything is an object. Even primitive datatypes (except null and undefined) can be treated as objects.

  • Booleans can be objects or primitive data treated as objects
  • Numbers can be objects or primitive data treated as objects
  • Strings are also objects or primitive data treated as objects
  • Dates are always objects
  • Maths and Regular Expressions are always objects
  • Arrays are always objects
  • Even functions are always objects

1.       String object: string object can be used to perform some operations on the string
<html>
 <head>
  </head>
<body>
 <script type="text/javascript">
   var name="java script"
   document.write("name"+name+"<br/>");
   document.write("length:"+name.length+"<br/>");
   document.write("uppercase:"+name.toUpperCase()+"<br/>");
   document.write("Lowercase:"+name.toLowerCase()+"<br/>);
   document.write("ColoredText:"+name.fontcolor("red")+"<br/>");
   document.write("Index:"name.indexOf("a")+"<br/>");
   document.write("Last index:"+name.lastIndexOf("a")+"<br/>");
   document.write("replace:"+name.replace("java","Viz")+"<br/>");
</script>
</body>
</html>


1.       Date: this object is used to retrieve the date and time.
<html>
 <head>
  </head>
   <body>
     <script type="text/javascript">
      var date=new Date();
      document.write("date:"+date+"<br/>");
      document.write("day:"+date.getDate()+"<br/>");
      document.write("Month:"+date.getMonth()+"<br/>");
      document.write("Year:"+date.getYear()+"<br/>");
      document.write("Hours:"+date.getHours()+"<br/>");
      document.write("minutes:"+date.getMinutes()+"<br/>");
      document.write("seconds:"+date.getSeconds()+"<br/>");
   </script>
 </body>
</html>




3. Boolean:
 this object represents either true or false.


Sunday, 11 August 2013

javascript Conditional statements

Conditional statements:
These statements are used to execute a block of code (statements) based on a condition.

1.       If statement
2.       If..else statement
3.       Switch statements
Iterative statements
1.       While
2.       Do..while()
3.       For()

1. if statement:
it is executed only when the condition is true
syntax:
if(condition)
{
  statement;
}
Ex:
<html>
 <head>
  <script type="text/javascript">
  if(2<7)
  {
   document.write("2 is smaller value");
  }
 </script>
 </head>
 </html>

2. if..else statements

 If the condition is true we execute if block otherwise we execute 'else' block.

syntax:
 if(condition)
 {
    statement1;
 }
else
{
  statement2;
}
Ex:
<html>
 <head>
  <script type="text/javascript">
   if(2<1)
   {
    document.write("2 is smaller value");
   }
   else
   {
    document.write("2 is bigger value");
   }
  </script>
 <head>
</html>
3. switch statement

the switch statement is used to execute a block of code from multiple blocks of codes.

Ex:
<html>
 <head>
  <script type="text/javascript">
  var no=parseInt(prompt("enter a number"));
  switch(no)
  {
   case 1: document.write("one");
          break;
   case 2: document.write("two");
          break;
   case 3: document.write("three");
          break;
   default: document.write("default");
  }
 </script>
 </head>
</html>
output:


 if you type any number (ex: 1)
it displays like below
Iterating statements:

confirm box

1.       Confirm box: this box is used to verify the user operation.
Syntax: confirm(message);
·         The confirm box contains two buttons “OK” and “CANCEL”
·         If the user clicks on “OK” it returns true value

·         If the user clicks on “CANCEL” it returns false value
//confirm.html
<html>
 <head>
  <script type="text/javascript">
  var status=confirm("do you want to exit")
  document.write("status:="+status);
  </script>
 </head>
 </html>
output:

if you click on "ok" button

if you click on "cancel" button




Popup boxes

Popup boxes:
1.       Alert box: this box is used to display a message to the user.
It ensures that the user reads the message and click on “OK” button because it will not allow the user to perform any operation without checking “OK” button.
Syntax: alert(“message”);

2.       Prompt box:
This box is used to provide information by the user.
The prompt box contains two buttons (1) OK (2) CANCEL
·         If the user click on “OK” button then it will read the information typed by the user from the user box.
·         If the user clicks on “CANCEL” button then it will read NULL value.

2nd Syntax: prompt(message, default-value);
<html>
 <head>
  <script type="text/javascript">
   var name=prompt("enter your name");
   document.write("name:"+name);
  </script>
 </head>
</html>

output:

enter any name in that popup box
and click on "ok" button