JavaScript Interview Questions and Answers Set 6

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

var number;//Here, number has undefined value.  

Null value: A value that is explicitly specified by the keyword “null” is known as null value. For example:

var str=null;//Here, str has a null value.  

52. How to submit a form using JavaScript by clicking a link?

Let’s see the JavaScript code to submit form on clicking the link.

<form name=”myform” action=”index.php”>  

Search: <input type=’text’ name=’query’ />  

<a href=”javascript: submitform()”>Search</a>  

</form>  

<script type=”text/javascript”>  

function submitform()  

{  

  document.myform.submit();  

}  

</script>  

53. How to change the background color of HTML document using JavaScript?

<script type=”text/javascript”>  

document.body.bgColor=”pink”;  

</script>  

54. How can you read properties of an Object in JavaScript?

You can write and read properties of an object using the dot notation as follows −

Getting object properties

emp.name  // ==> Zara

emp.age   // ==> 10

Setting object properties

emp.name = “Daisy”  // <== Daisy

emp.age  =  20      // <== 20

 

55. How can you create an Array in JavaScript?

You can define arrays using the array literal as follows −

var x = [];

var y = [1, 2, 3, 4, 5];

56. How to read elements of an array in JavaScript?

An array has a length property that is useful for iteration. We can read elements of an array as follows −

var x = [1, 2, 3, 4, 5];

for (var i = 0; i < x.length; i++) {

   // Do something with x[i]

}

57. What is a named function in JavaScript? How to define a named function?

A named function has a name when it is defined. A named function can be defined using function keyword as follows −

function named(){

   // do some stuff here

}

58. How to define a anonymous function?

An anonymous function can be defined in similar way as a normal function but it would not have any name.

 

59. Can you assign a anonymous function to a variable?

Yes! An anonymous function can be assigned to a variable.

 

60. What is the purpose of ‘this’ operator in JavaScript?

JavaScript famous keyword this always refers to the current context.