Basic Java Script interview Q & A



1. What are JavaScript Data Types?
Following are the JavaScript Data types:
  • Number
  • String
  • Boolean
  • Object
  • Undefined
2. What is the use of isNaN function?
isNan function returns true if the argument is not a number otherwise it is false.

3. Which company developed JavaScript?
Netscape is the software company who developed JavaScript.

4. What are undeclared and undefined variables?
  • Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.
  • Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.
5. Write the code for adding new elements dynamically?
<html> 
<head> 
<title>t1</title> 
<script type="text/javascript"> 
function addNode() { var newP = document.createElement("p"); 
var textNode = document.createTextNode(" This is a new text node"); 
newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); } 
</script> </head> 
<body> <p id="firstP">firstP<p> </body> 
</html>

6. What are global variables? How are these variable declared and what are the problems associated with using them?
  • Global variables are those that are available throughout the length of the code, that is, these have no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared.
Example:
// Declare a global globalVariable = "Test";

The problems that are faced by using global variables are the clash of variable names of local and global scope. Also, it is difficult to debug and test the code that relies on global variables.

7. What is a prompt box?
A prompt box is a box which allows the user to enter input by providing a text box. Label and box will be provided to enter the text or number.

8. What is 'this' keyword in JavaScript?
'This' keyword refers to the object from where it was called.

9. Explain the working of timers in JavaScript? Also elucidate the drawbacks of using the timer, if any?
Timers are used to execute a piece of code at a set time or also to repeat the code in a given interval of time. This is done by using the functions setTimeout, setInterval and clearInterval.

The setTimeout(function, delay) function is used to start a timer that calls a particular function after the mentioned delay. The setInterval(function, delay) function is used to repeatedly execute the given function in the mentioned delay and only halts when cancelled. The clearInterval(id) function instructs the timer to stop.

Timers are operated within a single thread, and thus events might queue up, waiting to be executed.

10. What is the difference between ViewState and SessionState?
  • 'ViewState' is specific to a page in a session.
  • 'SessionState' is specific to user specific data that can be accessed across all pages in the web application.
11. What is the difference between = = and = = = in javascript?
This is very common interview question in javascript most of the interviewer asked this kind of question the very basic example is:

  • 1 = = ‘1’ The result of this answer is true because when we compare two values using double equal then it comapares only value.
  • But 1 = = = ‘1’ this gives us false because this time not only checkes the value but its data type also.
12. Explain how can you submit a form using JavaScript?
To submit a form using JavaScript use document.form[0].submit();

document.form[0].submit();

13. How can the style/class of an element be changed?
It can be done in the following way:
document.getElementById("myText").style.fontSize = "20?;

or

document.getElementById("myText").className = "anyclass";

14. What are all the looping structures in JavaScript?
Following are looping structures in Javascript:
  • For
  • While
  • do-while loops
15. What is called Variable typing in Javascript?
Variable typing is used to assign a number to a variable and the same variable can be assigned to a string.

Example:

i = 10;
i = "string";
This is called variable typing.

16. How can you convert the string of any base to integer in JavaScript?
The parseInt() function is used to convert numbers between different bases. parseInt() takes the string to be converted as its first parameter, and the second parameter is the base of the given string.

In order to convert 4F (of base 16) to integer, the code used will be -

  • parseInt ("4F", 16);

17. What would be the result of 3+2+"7"?
Since 3 and 2 are integers, they will be added numerically. And since 7 is a string, its concatenation will be done. So the result would be 57.

18. What do mean by NULL in Javascript?
The NULL value is used to represent no value or no object. It implies no object or null string, no valid boolean value, no number and no array object.

19. What is the function of delete operator?
The delete keyword is used to delete the property as well as its value.

Example:

var student= {age:20, batch:"ABC"};
delete student.age;

20. What is an undefined value in JavaScript?
Undefined value means the:

  • Variable used in the code doesn't exist
  • Variable is not assigned to any value
  • Property doesn't exist

21. What are all the types of Pop up boxes available in JavaScript?

  • Alert
  • Confirm and
  • Prompt

22. What is the use of Void(0)?

  • Void(0) is used to prevent the page from refreshing and parameter "zero" is passed while calling.
  • Void(0) is used to call another method without refreshing the page.

23. What is the data type of variables of in JavaScript?

All variables in the JavaScript are object data types.

24. What is the difference between an alert box and a confirmation box?

  • An alert box displays only one button which is the OK button.
  • But a Confirmation box displays two buttons namely OK and cancel.

24. What are escape characters?
Escape characters (Backslash) is used when working with special characters like single quotes, double quotes, apostrophes and ampersands. Place backslash before the characters to make it display.

Example:

document.write "I m a "good" boy"
document.write "I m a \"good\" boy"

25. What are JavaScript Cookies?
Cookies are the small test files stored in a computer and it gets created when the user visits the websites to store information that they need. Example could be User Name details and shopping cart information from the previous visits.

26. Explain what is pop()method in JavaScript?
The pop() method is similar as the shift() method but the difference is that the Shift method works at the start of the array. Also the pop() method take the last element off of the given array and returns it. The array on which is called is then altered.

Example:

var cloths = ["Shirt", "Pant", "TShirt"];
cloths.pop();
//Now cloth becomes Shirt,Pant

27. Mention what is the disadvantage of using innerHTML in JavaScript?
If you use innerHTML in JavaScript the disadvantages are:

  • Content is replaced everywhere.
  • We cannot use like "appending to innerHTML".
  • Even if you use +=like "innerHTML = innerHTML + 'html'" still the old content is replaced by html.
  • The entire innerHTML content is re-parsed and build into elements, therefore its much slower.
  • The innerHTML does not provide validation and therefore we can potentially insert valid and broken HTML in the document and break it.

28. What is break and continue statements?

  • Break statement exits from the current loop.
  • Continue statement continues with next statement of the loop.

29. What are the two basic groups of dataypes in JavaScript?

They are as –

  • Primitive
  • Reference types.

Primitive types are number and Boolean data types. Reference types are more complex types like strings and dates.

30. How generic objects can be created?
Generic objects can be created as:

var I = new object();

31. What is the use of type of operator?

'Typeof' is an operator which is used to return a string description of the type of a variable.

 32. Which keywords are used to handle exceptions?

Try… Catch---finally is used to handle exceptions in the JavaScript

Try{
Code
}
Catch(exp){
Code to throw an exception
}
Finally{
Code runs either it finishes successfully or after catch
}

33. Which keyword is used to print the text in the screen?

document.write("Welcome") is used to print the text – Welcome in the screen.

34. What is the use of blur function?

Blur function is used to remove the focus from the specified object.

35. What is variable typing?

Variable typing is used to assign a number to a variable and then assign string to the same variable. Example is as follows:

i= 8;
i="john";

36. How to find operating system in the client machine using JavaScript?

The 'Navigator.appversion' is used to find the name of the operating system in the client machine.

37. What are the different types of errors in JavaScript?
There are three types of errors:

  • Load time errors: Errors which come up when loading a web page like improper syntax errors are known as Load time errors and it generates the errors dynamically.
  • Run time errors: Errors that come due to misuse of the command inside the HTML language.
  • Logical Errors: These are the errors that occur due to the bad logic performed on a function which is having different operation.

38. What is the use of Push method in JavaScript?

The push method is used to add or append one or more elements to the end of an Array. Using this method, we can append multiple elements by passing multiple arguments

39. What is unshift method in JavaScript?

Unshift method is like push method which works at the beginning of the array. This method is used to prepend one or more elements to the beginning of the array.

40. What is the 'Strict' mode in JavaScript and how can it be enabled?

Strict Mode adds certain compulsions to JavaScript. Under the strict mode, JavaScript shows errors for a piece of codes, which did not show an error before, but might be problematic and potentially unsafe. Strict mode also solves some mistakes that hamper the JavaScript engines to work efficiently.

Strict mode can be enabled by adding the string literal "use strict" above the file. This can be illustrated by the given example:

function myfunction() {
    "use strict";
    var v = "This is a strict mode function";
}

41. What is the way to get the status of a CheckBox?

The status can be acquired as follows -

alert(document.getElementById('checkbox1').checked);

If the CheckBox will be checked, this alert will return TRUE.

42. Explain window.onload and onDocumentReady?

The onload function is not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed.

onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the code.

42. How can a value be appended to an array?

A value can be appended to an array in the given manner -

arr[arr.length] = value;

43. Explain the for-in loop?

The for-in loop is used to loop through the properties of an object.

The syntax for the for-in loop is -

for (variable name in object){
statement or block to execute
}
In each repetition, one property from the object is associated to the variable name, and the loop is continued till all the properties of the object are depleted.

44. Describe the properties of an anonymous function in JavaScript?

A function that is declared without any named identifier is known as an anonymous function. In general, an anonymous function is inaccessible after its declaration.

Anonymous function declaration -

var anon = function() {
alert('I am anonymous');
};
anon();


45. What is the difference between .call() and .apply()?

The function .call() and .apply() are very similar in their usage except a little difference. .call() is used when the number of the function's arguments are known to the programmer, as they have to be mentioned as arguments in the call statement. On the other hand, .apply() is used when the number is not known. The function .apply() expects the argument to be an array.

The basic difference between .call() and .apply() is in the way arguments are passed to the function. Their usage can be illustrated by the given example.

var someObject = {
myProperty : 'Foo',

myMethod : function(prefix, postfix) {

alert(prefix + this.myProperty + postfix);
}
};
someObject.myMethod('<', '>'); // alerts '<Foo>'
var someOtherObject  = {

myProperty : 'Bar'

};
someObject.myMethod.call(someOtherObject, '<', '>'); // alerts '<Bar>'

someObject.myMethod.apply(someOtherObject, ['<', '>']); // alerts '<Bar>'

Comments