Monday 3 June 2013

Javascript Interview Questions and Answers


JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language is used most widely today in Web browsers whose software objects tend to represent a variety of HTML elements in a document and the document itself. You can change the DOM element and call the Ajax. It is independent of operating and language.


Question: How many types of loop are there in javaScript?

Answer: JavaScript supports following different types of loops
for - loops through a block of code a number of times
for/in - loops through the properties of an object
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true
/** for loop example **/
cars=["BMW","Volvo","Merchi","Ford"];
var i=2,len=cars.length;
for (; i");
}
/** for loop example **/

/** For/In Loop **/
var person={fname:"John",lname:"Doe",age:25}; 

for (x in person)
  {
alert(person[x]);
  }
/** For/In Loop **/

/** while loop **/
while (i<5 data-blogger-escaped-br="" data-blogger-escaped-he="" data-blogger-escaped-i="" data-blogger-escaped-is="" data-blogger-escaped-number="" data-blogger-escaped-x="x">";
  i++;
  }
/** while loop **/ 


Question:What are global variables? How are they declared? How these are different from local variables?
Answer: Variable that are available throughout the page.
These are declared without use of var keyword.

Variable that are declared with use of keyword var are local variable and available within scope.
// Declare a local variable
var localVariable = "PHP Tutorial"
// Declare a global
globalVariable = "google"
 


Question:What is the difference between undefined and null?
Answer: The value of a variable with no value is undefined (i.e., it has not been initialized). Variables can be emptied by setting their value to null. You can use === operator to test this.


Question: What are the various datatypes in javascript?
Answer: Number - Store Number like 1,100, 33
String - Store string like "php","tutorial-" etc
Boolean - Store true OR false
Function - Store the function
Object - Store the object like person object
Null - Store the variable value null
Undefined - Not defined variable value are undefined.


Question: What is negative infinity?
Answer: It’s a number in JavaScript, derived by dividing negative number by zero. For example var a=-100/0;

Question: How to check the type of variable?
Answertypeof is used to check the variable type. For example alert(typeof abc);


Question: How do you convert numbers between different bases in JavaScript?
Answer: Use the parseInt() function.
alert( parseInt ("3F", 16));


Question: What is Javascript namespacing? How and where is it used?
Answer: 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.


Question: How to load javascript files asynchronously?
Question: How to load javascript files fast?
 Answer: If you have latest browser which support HTML5 then you just need to add "async" tag with value true
If you have old browser, you need to create a js function that will add javascript async Following are the Javascript function example
function loadScriptAsync (scriptFilePath){
    var scriptHeadTag=document.getElementsByTagName('script')[0];
    var ss=document.createElement('script');
    ss.type='text/javascript';
    ss.async=true;
    ss.src= scriptFilePath
    scriptHeadTag.parentNode.insertBefore(ss,s);
}

loadScriptAsync('/js/jsfile.js'); 

Pass PHP Array into Ajax Call
//Setp 1: Include jQuery file in your page

$phpData = array('fname'=>'G', 'lname'=>'Geo','email'=>'g7789@gmaill.com'); //Setp 2: This is your PHP Array data

 [script]
/** Setp 3: This is Ajax Call will be called after page fully load **/
     function saveuserdetail(mydata) {                                    
                    $.ajax({
                        type: "POST",//Here you can use POST/GET Method
                        url: '/postpageurl/',
                        data: mydata,
                        success: function(msg){                            
                            console.log('Data'+msg);
                        },
                        dataType: 'json'
                    });                
            }
/** This is Ajax Call will be called after page fully load **/


/* Step 4: When Page Load, PHP Array will convert into javaScript Object */
/* Pass the javaScript Object into javaScript Function i.e saveuserdetail**/
$( document ).ready(function() {
    var data=new Object("echo json_encode($phpData) ")
    saveuserdetail(data);
});
[/script]

Question: Is JavaScript case sensitive?
Answer: Yes!
getElementById is different from getElementbyID.


Question: How will you get the Checkbox status whether it is checked or not?
Answer:
alert(document.getElementById('checkbox1').checked);


Question: How do you submit a form using JavaScript?
Answer:
document.forms[0].submit();


Question: What does isNaN function do?
Answer: isNaN : IsNotaNumber
returns true if the argument is not a number;

Question: What does "1"+9+4 evaluate to?
Answer: 194

How do you assign object properties?
obj["age"] = 22 or obj.age = 22.



What’s a way to append a value to an array?
arr[arr.length] = value;


How to read and write a file using javascript?
 I/O operations like reading or writing a file is not possible with client-side javascript.



How do you convert numbers between different bases in JavaScript?
Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal FF to decimal, use parseInt ("FF", 16);



What is negative infinity? 
It’s a number in JavaScript, derived by dividing negative number by zero.



How to set a HTML document's background color?
 document.bgcolor property can be set to any appropriate color.



What boolean operators does JavaScript support?
&&, and !



How to get the contents of an input box using Javascript?
 Use the "value" property.var myValue = window.document.getElementById("textboxID").value;



How to determine the state of a checkbox using Javascript? 
var checkedP = window.document.getElementById("CheckBoxID").checked;



How to set the focus in an element using Javascript? 
<script> function setFocus() { if(focusElement != null) { document.forms[0].elements["myelementname"].focus(); } } </script>



How to access an external javascript file that is stored externally and not embedded? 
This can be achieved by using the following tag between head tags or between body tags.<script src="raj.js"></script>How to access an external javascript file that is stored externally and not embedded? where abc.js is the external javscript file to be accessed.



What is the difference between an alert box and a confirmation box? 
An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel.



What is a prompt box? 
A prompt box allows the user to enter input by providing a text box.



Can javascript code be broken in different lines?
Breaking is possible within a string statement by using a backslash \ at the end but not within any other javascript statement.that is ,document.write("Hello \ world");is possible but not document.write \("hello world");



What looping structures are there in JavaScript?
for, while, do-while loops, but no foreach.



How do you create a new object in JavaScript?
var obj = new Object(); or var obj = {};



What is this keyword?
It refers to the current object.


What is the difference between SessionState and ViewState? 
ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the web application.

What looping structures are there in JavaScript? 
for, while, do-while loops, but no foreach.



To put a "close window" link on a page ? 
<a href='javascript:window.close()'> Close </a>



How to comment javascript code? 
Use // for line comments and/**/ for block comments



Name the numeric constants representing max,min values 
Number.MAX_VALUENumber.MIN_VALUE



What does javascript null mean? The null value is a unique value representing no value or no object.It implies no object,or null string,no valid boolean value,no number and no array object.



How do you create a new object in JavaScript? 
var obj = new Object(); or var obj = {};



How do you assign object properties? 
obj["age"] = 23 or obj.age = 23.



What’s a way to append a value to an array? 
arr[arr.length] = value;


What does undefined value mean in javascript? 
Undefined value means the variable used in the code doesn't exist or is not assigned any value or the property doesn't exist.



What is the difference between undefined value and null value? 
(i)Undefined value cannot be explicitly stated that is there is no keyword called undefined whereas null value has keyword called null(ii)typeof undefined variable or property returns undefined whereas typeof null value returns object



What is variable typing in javascript? It is perfectly legal to assign a number to a variable and then assign a string to the same variable as followsexamplei = 10;i = "string";This is called variable typing



Does javascript have the concept level scope? No. JavaScript does not have block level scope, all the variables declared inside a function possess the same level of scope unlike c,c++,java.

What is === operator ? ==== is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion.

How to disable an HTML object ?
document.getElementById("myObject").disabled = true;



How to create a popup warning box?
alert('Warning: Please enter an integer between 0 and 1000.');



How to create a confirmation box? 
confirm("Do you really want to launch the missile?");



How to create an input box? 
prompt("What is your temperature?");


What's Math Constants and Functions using JavaScript? 
The Math object contains useful constants such as Math.PI, Math.EMath.abs(value); //absolute valueMath.max(value1, value2); //find the largestMath.random() //generate a decimal number between 0 and 1Math.floor(Math.random()*101) //generate a decimal number between 0 and 100



What does the delete operator do? 
The delete operator is used to delete all the variables and objects used in the program ,but it does not delete variables declared with var keyword.



How to get value from a textbox?
alert(document.getElementById('txtbox1').value);



How to get value from dropdown (select) control?alert(document.getElementById('dropdown1').value);


What is console.log?
It is feature of Firebug used for debug the javascript OR jQuery code. It can print the string, number, array OR object. It is same as print_r() in php.

Example of console.log
console.log (22 );
console.log ('web technology experts notes' );
console.log (arrayVal);
console.log (objectVal);



Question: How to check checkbox is checked or not in jquery?
$('.checkBoxClass').is(':checked');


Question: How to check the checkbox as checked?
$(".checkBoxClass").attr('checked', true); // Deprecated
$(".checkBoxClass").prop('checked', true);


Best Related Posts are Following:
1. jQuery Mobile interview questions and answers
2. Ajax Interview questions and answers for experienced
3. Advanced MySQL Interview Questions and Answers for Experienced
4. SAML Interview Questions and Answers
5. HTML5 interview Questions and Answers for Fresher and Experienced
6. Backbone Js interview questions and answers
7. Bootstrap Interview Questions and Answers for Experienced
8. HTML interview questions and Answers
9. SEO Interview Questions and Answers
10. AngularJS Interview Questions and Answers for Experienced
11. Difference Between Hadoop and Big-Data
12. Memcached interview questions and answers
13. General Interview Questions and Answers
14. UNIX Commands Interview Questions and Answers
15. Apache Interview Questions and Answers
16. PHP Technical Interview Questions and Answers
17. Zend Framework Interview Questions and Answers for Experienced - Page 2
18. CSS Interview Questions and Answers
19. Mysql Interview Questions And Answers - Atomicity, Dedlock, Client Program, Mysql Mode, Mysql Sensitivity Of Identifiers And Mysql Errors
20. Zend Framework Interview Questions and Answers for Experienced
21. XML Interview Questions And Answers