Dear Readers, Welcome to JavaScript Interview questions with answers and explanation.

If you are a job hunter and looking for job in web development or web designing, you must have to know javaScript to crack interviews.The commonly asked interview questions and answers for HTML are given below.

If there is any other javaScript interview question that have been asked to you, kindly post it in the the comment section.


1. What is JavaScript?


JavaScript is a client-side as well as server side scripting language that can be inserted into HTML pages and is understood by web browsers. JavaScript is also an Object based Programming language

2. Enumerate the differences between Java and JavaScript?


Java is a complete programming language. In contrast, JavaScript is a coded program that can be introduced to HTML pages. These two languages are not at all inter-dependent and are designed for the different intent. Java is an object – oriented programming (OOPS) or structured programming language like C++ or C whereas JavaScript is a client-side scripting language.

3. What are JavaScript Data Types?


Following are the JavaScript Data types:

  • Number
  • String
  • Boolean
  • Function
  • Object
  • Undefined

4. What is the use of isNaN function?


isNan function returns true if the argument is not a number otherwise it is false.

5. Between JavaScript and an ASP script, which is faster?


JavaScript is faster. JavaScript is a client-side language and thus it does not need the assistance of the web server to execute. On the other hand, ASP is a server-side language and hence is always slower than JavaScript. Javascript now is also a server side language (nodejs)

6. What is negative infinity?


Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.

7. Is it possible to break JavaScript Code into several lines?


Breaking within a string statement can be done by the use of a backslash, ‘\’, at the end of the first line

document.write(“This is \a program”);
And if you change to a new line when not within a string statement, then javaScript ignores break in line.


var x=1, y=2,

The above code is perfectly fine, though not advisable as it hampers debugging.

8. Which company developed JavaScript?


Netscape is the software company who developed JavaScript.

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

10. Write the code for adding new elements dynamically?


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


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

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

13. What is ‘this’ keyword in JavaScript?


‘This’ keyword refers to the object from where it was called.

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

15. Which symbol is used for comments in Javascript?


// for Single line comments and
/* Multi

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

17. What is === operator?


=== is called as strict equality operator which returns true when the two operands are having the same value without any type conversion.

18. Explain how can you submit a form using JavaScript?


To submit a form using JavaScript use document.form[0].submit();

19. Does JavaScript support automatic type conversion?


Yes JavaScript does support automatic type conversion, it is the common way of type conversion used by JavaScript developers

20. How can the style/class of an element be changed?


It can be done in the following way:

document.getElementById(“myText”).style.fontSize = “20?;


document.getElementById(“myText”).className = “anyclass”;


21. Explain how to read and write a file using JavaScript?


  • There are two ways to read and write a file using JavaScript
  • Using JavaScript extensions
  • Using a web page and Active X objects

22. What are all the looping structures in JavaScript?


Following are looping structures in Javascript:

  • For
  • While
  • do-while loops

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


i = 10;
i = “string”;

This is called variable typing.

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

25. Explain the difference between “==” and “===”?


“==” checks only for equality in value whereas “===” is a stricter equality test and returns false if either the value or the type of the two variables are different.

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

27. Explain how to detect the operating system on the client machine?


In order to detect the operating system on the client machine, the navigator.platform string (property) should be used.

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

29. What is the function of delete operator?


The functionality of delete operator is used to delete all variables and objects in a program but it cannot delete variables declared with VAR keyword.

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


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


  • Alert
  • Confirm and
  • Prompt

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

33. How can a page be forced to load another page in JavaScript?


The following code has to be inserted to achieve the desired effect:

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


All variables in the JavaScript are object data types.

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

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


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

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

38. 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.
var cloths = [“Shirt”, “Pant”, “TShirt”];
//Now cloth becomes Shirt,Pant

39. Whether JavaScript has concept level scope?


No. JavaScript does not have concept level scope. The variable declared inside the function has scope inside the function.

40. Mention what is the disadvantage of using innerHTML in JavaScript?


If you use innerHTML in JavaScript the disadvantage is

  • 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


41. What is break and continue statements?


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

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

43. How generic objects can be created?


Generic objects can be created as:

var I = new object();

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

45. Which keywords are used to handle exceptions?


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

Code to throw an exception
Code runs either it finishes successfully or after catch

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


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

47. What is the use of blur function?


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

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

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

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


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

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

53. What is the difference between JavaScript and Jscript?


Both are almost similar. JavaScript is developed by Netscape and Jscript was developed by Microsoft .

54. How are object properties assigned?


Properties are assigned to objects in the following way –

obj["class"] = 12;


obj.class = 12;

55. 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";

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


The status can be acquired as follows –
If the CheckBox will be checked, this alert will return TRUE.

57. How can the OS of the client machine be detected?


The navigator.appVersion string can be used to detect the operating system on the client machine.

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

59. How will you explain closures in JavaScript? When are they used?


Closure is a locally declared variable related to a function which stays in memory when the function has returned.
For example:

function greet(message) {
function greeter(name, age) {
return name + " says howdy!! He is " + age + " years old";
// Generate the message
var message = greeter("James", 23);
// Pass it explicitly to greet
This function can be better represented by using closures
function greeter(name, age) {
var message = name + " says howdy!! He is " + age + " years old";
return function greet() {
// Generate the closure
var JamesGreeter = greeter("James", 23);
// Use the closure

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


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

62. 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');

63. 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 ''
var someOtherObject = {
myProperty : 'Bar'
};, '<', '>'); // alerts ''
someObject.myMethod.apply(someOtherObject, ['<', '>']); // alerts ''

64. Define event bubbling?


JavaScript allows DOM elements to be nested inside each other. In such a case, if the handler of the child is clicked, the handler of parent will also work as if it were clicked too.

65. Is JavaScript case sensitive? Give an example?


Yes, JavaScript is case sensitive. For example, a function parseInt is not same as the function Parseint.

66. What boolean operators can be used in JavaScript?


The ‘And’ Operator (&&), ‘Or’ Operator (||) and the ‘Not’ Operator (!) can be used in JavaScript.
*Operators are without the parenthesis.

67. How can a particular frame be targeted, from a hyperlink, in JavaScript?


This can be done by including the name of the required frame in the hyperlink using the ‘target’ attribute.

<a href=”newpage.htm” target=”newframe”>>New Page</a>

68. What is the role of break and continue statements?


Break statement is used to come out of the current loop while the continue statement continues the current loop with a new recurrence.

69. Write the point of difference between web-garden and a web-farm?


Both web-garden and web-farm are web hosting systems. The only difference is that web-garden is a setup that includes many processors in a single server while web-farm is a larger setup that uses more than one server.

70. How are object properties assigned?


Assigning properties to objects is done in the same way as a value is assigned to a variable. For example, a form object’s action value is assigned as ‘submit’ in the following manner – Document.form.action=”submit”


71. What is the method for reading and writing a file in JavaScript?


This can be done by Using JavaScript extensions (runs from JavaScript Editor), example for opening of a file –

fh = fopen(getScriptPath(), 0);

72. How are DOM utilized in JavaScript?


DOM stands for Document Object Model and is responsible for how various objects in a document interact with each other. DOM is required for developing web pages, which includes objects like paragraph, links, etc. These objects can be operated to include actions like add or delete. DOM is also required to add extra capabilities to a web page. On top of that, the use of API gives an advantage over other existing models.

73. How are event handlers utilized in JavaScript?


Events are the actions that result from activities, such as clicking a link or filling a form, by the user. An event handler is required to manage proper execution of all these events. Event handlers are an extra attribute of the object. This attribute includes event’s name and the action taken if the event takes place.

74. Explain the role of deferred scripts in JavaScript?


By default, the parsing of the HTML code, during page loading, is paused until the script has not stopped executing. It means, if the server is slow or the script is particularly heavy, then the webpage is displayed with a delay. While using Deferred, scripts delays execution of the script till the time HTML parser is running. This reduces the loading time of web pages and they get displayed faster.

75. What are the various functional components in JavaScript?


The different functional components in JavaScript are-

  • First-class functions: Functions in JavaScript are utilized as first class objects. This usually means that these functions can be passed as arguments to other functions, returned as values from other functions, assigned to variables or can also be stored in data structures.
  • Nested functions: The functions, which are defined inside other functions, are called Nested functions. They are called ‘everytime’ the main function is invoked.

76. Write about the errors shown in JavaScript?


JavaScript gives a message if it encounters an error. The recognized errors are –
Load-time errors: The errors shown at the time of the page loading are counted under Load-time errors. These errors are encountered by the use of improper syntax, and thus are detected while the page is getting loaded.
Run-time errors: This is the error that comes up while the program is running. It is caused by illegal operations, for example, division of a number by zero, or trying to access a non-existent area of the memory.
Logic errors: It is caused by the use of syntactically correct code, which does not fulfill the required task. For example, an infinite loop.

77. What are Screen objects?


Screen objects are used to read the information from the client’s screen. The properties of screen objects are

AvailHeight: Gives the height of client’s screen
AvailWidth: Gives the width of client’s screen.
ColorDepth: Gives the bit depth of images on the client’s screen
Height: Gives the total height of the client’s screen, including the taskbar
Width: Gives the total width of the client’s screen, including the taskbar

78. Explain the unshift() method ?


This method is functional at the starting of the array, unlike the push(). It adds the desired number of elements to the top of an array. For example –

var name = [ "john" ];
name.unshift( "charlie" );
name.unshift( "joseph", "Jane" );

The output is shown below:

[" joseph "," Jane ", " charlie ", " john "]

79. Define unescape() and escape() functions?


The escape () function is responsible for coding a string so as to make the transfer of the information from one computer to the other, across a network.
For Example:

document.write(escape(“Hello? How are you!”));

Output: Hello%3F%20How%20are%20you%21

The unescape() function is very important as it decodes the coded string.

It works in the following way. For example:


Output: Hello? How are you!

80. What are the decodeURI() and encodeURI()?


EncodeURl() is used to convert URL into their hex coding. And DecodeURI() is used to convert the encoded URL back to normal.

Output –
my test.asp?name=ståle&car=saab


81. Why it is not advised to use innerHTML in JavaScript?


innerHTML content is refreshed every time and thus is slower. There is no scope for validation in innerHTML and, therefore, it is easier to insert rouge code in the document and, thus, make the web page unstable.

82. What does the following statement declares?


var myArray = [[[]]];

It declares a three dimensional array.

83. How are JavaScript and ECMA Script related?


ECMA Script are like rules and guideline while Javascript is a scripting language used for web development.

84. What is namespacing in JavaScript and how is it used?


Namespacing is used for grouping the desired functions, variables etc. under a unique name. It is a name that has been attached to the desired functions, objects and properties. This improves modularity in the coding and enables code reuse.

85. How can JavaScript codes be hidden from old browsers that don’t support JavaScript?


For hiding JavaScript codes from old browsers:
Add “<!–” without the quotes in the code just after the

86. By Object Literal.


The syntax of creating an object using object literal is as follows.
object={property1:value1, property2:value2…..propertyN:valueN}
Here, property and value are separated by “:”.
Let’s take an example of creating an object using object literal technique.

87. By Creating An Instance Of The Object (Using New Keyword).


The syntax of creating an object directly is as follows.
var objectname=new Object();
Here, the new keyword is used to create the object.
Let’s take an example of creating an object directly.

88. By Using An Object Constructor.


In this method, we create a function with arguments. The value of each of these arguments can be assigned to the current object by using this keyword.
This keyword refers to the current object.
Let’s take an example of creating an object using object constructor technique.

89. What Is Scope In JavaScript?


The scope determines the accessibility of variables, objects, and functions in particular part of your code.
In JavaScript, the scope is of two types.
1. Global Scope.
A variable defined outside a function comes under the Global scope. Variables defined inside the Global scope are accessible from any part of the code. Let’s see an example.

var name = 'TechBeamers';
console.log(name); // logs 'TechBeamers'
function logName() {
console.log(name); // 'name' is accessible here and everywhere else
logName(); // logs 'TechBeamers'

2. Local Scope.
Variables defined inside a function comes under the Local scope. Different functions can use a variable with the same name. It is because these variables are strictly bound to the function that defines it (each having different scopes) and is not accessible in other functions. Let’s see an example.

// Global Scope
function sampleFunction() {
// Local Scope #1
function sample2Function() {
// Local Scope #2
// Global Scope
function sample3Function() {
// Local Scope #3
// Global Scope

90. What Is In JavaScript?


All the prime languages use ‘this’ keyword to refer to an object that is currently instantiated by the class. However, in JavaScript, ‘this’ refers to an object which ‘owns’ the method. Though this varies, with how a function call happens.
Global Scope.
If no object is currently available, then ‘this’ represents the global object. In a web browser, ‘window’ is the top-level object which represents the document, location, history and a few other useful properties and methods. Let’s take a sample code.

window.Obj= "I represent the window object";
alert(this.Obj); // I'm the window object
alert(window === this); // true

The Scenario Of A Function Call.
In the case of a function call, ‘this’ refers to the global object.

window.Obj = "I represent the window object";
function TestFunction() {
alert(this.Obj); // I'm the window object
alert(window === this); // true
Call Object Methods.
When an object constructor or any of its methods gets called, ‘this’ refers to an instance of an object. It is similar to any class-based language.
window.Obj = "I'm the window object";
function TestFunction() {
this.Obj = "I'm the Test object";
this.Verify1 = function() {
alert(this.Obj); // I'm the Test object
TestFunction.prototype.Verify2 = function() {
alert(this.Obj); // I'm the Test object
var tf= new TestFunction();


91. What Is Prototype Property In JavaScript?


Every JavaScript function has a prototype property (by default this property is null), that is mainly used for implementing inheritance. We add methods and properties to a function’s prototype so that it becomes available to instances of that function. Let’s take an example that calculates the perimeter of a rectangle.
function Rectangle(x, y) {
this.x = x;
this.y = y;
Rectangle.prototype.perimeter = function() {
return 2 * (this.x + this.y);
var rect = new Rectangle(4, 2);
console.log(rect.perimeter()); // outputs ’12’

92. What Is Closure In JavaScript?


A closure is a JavaScript function defined inside another function. And that’s why it gets a special privilege to access three types of scope which are as follows.

  • Internal Scope i.e. the variables defined between its curly brackets.
  • Outer Function Scope i.e. the variables of the enclosing function.
  • Global Scope i.e. variables defined as globals.
  • Please note that a closure can not only access the outer function variables but also see its parameters. But it can’t call the outer function’s arguments object. However, it can directly call the outer function’s parameters.
  • Here is a code example describing closure by adding a function inside another function.
function outerFunc(arg1, arg2) {
var param = "I'm closure. ";
// Inner function accessing outer function variables and parameters
function innerFunc() {
return arg1 + arg2 + " " + param;
return innerFunc();
outerFunc("arg1", "arg2");

93. Why Is “Self” Needed Instead Of “This” In JavaScript?


Inner functions in JavaScript have access to all of the variables defined in the outer function. However, “this” variable is an exception. Since the nested function is just a regular function and not an object method, it’s “this” refers to the global namespace. To make it more clear, let’s look at the following example.

var aProperty = 'global';
var myObject = {
outerFun: function() {
this.aProperty = 'local';
setTimeout(function() {
console.log(this.aProperty); // outputs 'global'
}, 1);

Thus, we see that inside “setTimeout” function, “this” refers to the global object. We need a way to get a reference to the object, that is available inside the nested function. We assign the object from “this”, to another(non-special) variable, “self”. It is not a special variable and hence cannot be overwritten by other functions(like “this”). Thus on using “self” inside the inner function, we can refer to the local object. Following is the sample code.

var myObject = {
outerFun: function() {
var self = this;
this.aProperty = 'local';
setTimeout(function() {
console.log(self.aProperty); // outputs 'local'

}, 1);

94. What Is An Anonymous Function And When Should You Use It?


Anonymous functions are functions that are dynamically declared at runtime. They’re called anonymous functions because they don’t have a name like normal functions.
We use function operator to declare an anonymous function, instead of the function declaration. Also, function operator can be used to create a new function, wherever it’s valid to put an expression. For example, we declare a new function to be supplied as an argument to a function call or to assign a property of another object.
Here’s a typical example of a named function.

function testFunction()

Here’s the same example created as an anonymous function.

var testFunction= function()
alert(“Zoom! Zoom! Zoom!”);

Following are the key usage of anonymous functions.

1. Code brevity.

  • Use them in
  • Callbacks, and
  • Event handlers.

2. Scope management.

  • They are useful in the following scenario.
    • To create temporary/private scope.
    • In Closures and Recursions.

95. What Is The Difference Between “==” And “===”?


These are the operators provided by JavaScript – strict equality and Type converting equality.
Strict equality (===) returns true if the values which it is going to compare have the same data type. Taking an example, “2” will not be equal to 2 i.e. (“2?===2) will return false.
Secondly, Type converting equality (==), automatically converts the variable to value irrespective of the data type. Taking an example, here “2” will be equal to 2 i.e. (“2?===2) will return true.
Summarizing it, double equal (==) is an autotype converting equality operator while three equals (===) is a strict equality operator, i.e. it will not convert values automatically.

96. What Are JavaScript Data Types?


JavaScript supports three Primary, two Composite and two Special data types. Next, we list down the data types in each of the categories.

Primary Data Types.

  • String
  • Number
  • Boolean

Composite Data Types.

  • Object
  • Array

Special Data Types.

  • Null
  • Undefined

97. What Is Prototypal Inheritance In JavaScript?


Most of the Object Oriented languages support classes and objects. Here, Classes inherit from other classes.
In JavaScript, the inheritance is prototype-based. This means that there are no classes. Instead, there is an object that inherits from another object.
JavaScript provides three different types of Prototypal Inheritance.

1. Delegation (I.E. The Prototype Chain).
A delegate prototype is an object that serves as a base for another object. When you inherit from a delegate prototype, the new object gets a reference to the prototype.
When we try to access any property, it first checks in the properties owned by the object. If that property does not exist there, it checks in the ‘[[Prototype]]’ and so on. If that property does not exist there, it checks in the ‘[[Prototype]]’ and so on. Gradually, it moves up the prototype chain, until it reaches the i.e. the root delegate for most of the objects.

2. Concatenative Inheritance (I.E. Mixins, Object.Assign()).
It is the process of inheriting the features of one object to another by copying the source objects properties. JavaScript calls these source prototypes by the name mixins. This process makes use of the JavaScript method Object.assign(). However, before ES6, the <.extend()> method was used.

3. Functional (Not To Be Confused With Functional Programming).
In JavaScript, a function can create an object. It’s not necessary to be a constructor(or a class). It is called a factory function. Functional inheritance produces an object from a factory and also extends it, by assigning properties.
Every type of Prototypal Inheritance supports a separate set of use-cases, applicable to it. All of them are equally useful in their ability to enable composition. It provides has-a, uses-a, or can-do relationship as compared to the is-a relationship created with class inheritance.

98. What Is An Asynchronous Programming? Why Is It Important In JavaScript?


In Asynchronous programming, the engine runs in an event loop. On encountering a blocking operation, a request gets fired and the code keeps running without blocking for the result. When its execution completes, and the response is ready, it fires an interrupt, which causes an event handler to be run, where the control flow continues. In this way, a single program thread can handle many concurrent operations in an asynchronous programming.
The user interface is asynchronous by nature and spends most of the time, waiting for user input to interrupt the event loop and trigger event handlers. Node is asynchronous by default. It means that the server works by waiting for a network request in a loop. Thus, it accepts more incoming requests, while the first one is getting handled.
It is important in JavaScript because it’s suitable for user interface code and beneficial for maintaining the performance on the server.

99. What Is Variable Typing In JavaScript?


JavaScript is very loosely typed language. It means that the variables are declared without a type. Its type is determined once a value is assigned to it. It can change as the variable appears in different contexts.
It’s in contrast to the strongly typed languages that require type declarations.
Consider the following examples.

/* JavaScript Example (loose typing) */ 
var a = 13; // Number declaration
var b = "thirteen"; // String declaration
/* Java Example (strong typing) */
int a = 13; // int declaration
String b = "thirteen"; // String declaration

Variable type in JavaScript is determined internally. In the above example, var ‘a’ will be of type ‘Number’ and var ‘b’ will be of type ‘String’.

100. What Are The Different Ways To Create An Array In JavaScript?


There are two main ways to create an array in JavaScript.
1. Using An Array Initializer (Array Literal).
The array initializer (array literal) syntax is simple. It is a comma-separated list of values in square brackets.
Let’s see some examples.

var myArray1 = [1,2,3,4,5] // an array with 5 elements
var myArray2 = [5] // an array with 1 element
var myArray3 = [true,'Hi',[7]] // element types need not be the same.

2. Using The Array Constructor.
The Array constructor method has three different syntaxes. If we call the constructor with two or more arguments, it declares an array with array elements also initialized. If we provide only one argument to the Array constructor, it refers to the length of the new array with, elements not initialized. Lastly, the constructor without any argument creates an array with its length set to zero with elements not initialized.
Let’s see some examples.

var myArray4 = new Array(1,2,3,4,5) // an array with 5 elements
var myArray5 = new Array(20) // an empty array of length 20
var myArray6 = new Array() // an empty array of length 0


101. What Are JavaScript Cookies?


A cookie is a piece of data which is sent from a website (that owns the requested web page) and gets stored locally by the browser at the user end. Cookies are needed because HTTP protocol which arranges for the transfer of web pages to your browser, is stateless. It means that HTTP has no way to keep track of the activities performed by the user at an earlier point in time. One way to resolve this issue is by using cookies. It contains following data.

  • A name-value pair containing the actual data.
  • An expiry date after which the cookie is no longer valid.
  • The domain and path of the server it should be sent to.

When a request arrives at the server for a web page that maintains a cookie, the server appends the cookie to the HTTP header to send it across. Server side programs can then read out the information included in it and decide that you have the right to view the page or not and other user preferences.
Thus, every time you visit the site that maintains the cookies, your information is available there.

102. Which Built-In Method Adds One Or More Elements To The End Of An Array And Returns The New Length Of The Array?


The push() method adds one or more elements to the end of an array and returns the new length of the array.

103. What Is The Naming Conventions For The Variables In JavaScript?


We have to follow the below rules while naming the variables in JavaScript.

  • Do not use any of the JavaScript reserved keywords as a name for your variable. For example, “break” or “boolean” are JavaScript keywords, and if used as variable names, it’s invalid.
  • JavaScript variable names should not start with a numeral (0-9). It must begin with a letter or the underscore character. For example, 123var is an invalid variable name, but _123var is a valid one.
  • Also, JavaScript variable names are case sensitive. For example, test and Test are two different variables.

104. How Will You Create A Cookie Using JavaScript?


The simplest way to create a cookie is to assign a string value to the object.
Its syntax is as follows.
document.cookie = “key1 = value1; key2 = value2; expires = date”;
Here, “expires” attribute is optional. We have to provide a date or time value for this attribute.
If we provide a valid value for the date or time, then the cookie will expire at the given date or time and it will not be accessible after that.

105. How To Read A Cookie Using JavaScript?


To read a Cookie, we have to access the value of the object. This string maintains a list of pairs that is separated with semicolons.
“name” is the name of a cookie and
“value” is its string value.
We use String <split()> function to break the object to sub-strings. Each of these sub-strings contains a key-value pair which represents the information related to a Cookie.

106. How To Delete A Cookie Using JavaScript?


To delete a Cookie, we have to set its expiry date to a time that occurred in the past. If attempts are made to read a deleted Cookie then, nothing is returned.

107. How Do You Submit A Form Using JavaScript?


We use the following in the web page code to submit a form.
Here <0> refers to the index of the form. If we have more than one forms on a web page, then the index for the first one will be “0”, for the second form, its value will be “1” and so on.

108. Why Should You Not Prefer To Use Global Variables In JavaScript And How Can You Prevent It?


The principal issue in using a global variable is that someone else can create another variable with the same name. And you may not know it until the duplicate could overwrite the value of your variable.
To avoid using globals, follow any of the following approaches.
1. Create a single global variable that holds all your other variables.

var myGlobalList = {};
myGlobalList.first = "test";

2. Enclose all of your code in a self-executing method/function so that any variable declared inside remain in the function scope.

var test = "myvar";

109. What Are The Different Objects Used In JavaScript?


JavaScript uses a hierarchical structure, applicable to all the objects created in a document. Following are the objects, used in JavaScript that shows the relationship of one object to another.

Window Object

It is the topmost object in the hierarchy. It refers to the content area of the browser window that consists of HTML documents. Each frame is also a window that has some actions inside it.

Document Object

A Document object represents the HTML document that the window will display. It has various properties that refer to other objects, which allow access to and modification of content in the document.

Form Object

A form object is used to take user data as input for processing. It corresponds to an HTML input form constructed with the



110. What Do We Achieve By Deferring The Loading Of JavaScript?


During page load operation, by default, the parsing of the HTML code remains paused until the execution of the script has not stopped.
Now, if the script is heavy or the server is slow, then this will result in a delay in displaying the web page.
By deferring the loading of JavaScript, we instruct the browser to load the script, only after the loading of the web page(DOM) has finished. It reduces the loading time of the webpage, and it gets displayed faster.
In this way, it makes the page load quicker, without the average user even realizing that some JavaScript load after the DOM has loaded.
Let’s see an example.


// this piece of code runs first


<script defer="defer">

//do stuff, but defer it (runs last)



//do more stuff (runs second)


Here the middle block will execute once the page has loaded even though it appears before the last block.


111. What Is Strict Mode In JavaScript?


Strict Mode imposes a layer of constraint on JavaScript. It provides following enhancements.

  • JavaScript will throw an error if we try to use the elements of a deprecated language.
  • To use a variable, it has become mandatory to declare it.
  • It disallows duplicate property and parameter names.
  • The eval() method is safer to use, but still considered evil in some cases.
  • It deprecates the “with” statement.
  • JavaScript will throw an error if we try to assign a value to a read-only property.
  • It decreases the global namespace pollution.

To enable strict mode, we have to add, “use strict” directive to the code. The physical location of the “strict” directive determines its scope. If used at the beginning of the js file, its scope is global. However, if we declare strict mode at the first line in the function block, its scope restricts to that function only.

112. What Are Event Handlers In JavaScript And How To Use Them?


JavaScript event handlers are functions that bind to a specific HTML DOM event. And events are the part of HTML document object model (DOM). An event can take place in one of the following cases.
Due to user actions on a web page.
<onclick()>, <onmouseover()>, <onkeydown()>
Some events are callbacks triggered by the browser when a page changes its state.
<onload()>, <onunload()>, <onresize()>

Whenever the DOM receives an event, it calls the JavaScript event handler function bind to the event. To use a handler function, we can assign it to the desired event as an attribute of the target HTML element. Please follow the below example.




<INPUT TYPE=”button” VALUE=”Test” onClick=”window.alert ('Event Handler')”>




113. What Does A JavaScript Function Result When It Has No Return Statement?


If a function doesn’t use the return statement, then it returns undefined as the return value.
However, the browser won’t print anything in its console as it ignores if the expression returns an undefined value. But if we explicitly call such a function inside the console.log() method, then it’ll print exact value.

function test(){}
console.log(test()); // will print 'undefined'

114. How Does The <Array()> Differ From <[]> While Creating A JavaScript Array?


Both the <Array()> and <[]> works almost the same in JavaScript.
If we use them as is (i.e. without any argument) to create an array object, then they will result in an array object of zero length. Also, if we pass a string or a list of strings as arguments, even then result will be similar.
However, they differ when the input argument is of integer type. In that case, the <Array(n)> statement will create an uninitialized array of size of n. Whereas, the <[n]> statement will create an array of size <1>and assign as value to the first element.

115. How Does Variable Hoisting Take Place In JavaScript?


In JavaScript, variable declarations are the first piece of code that executes irrespective of their location. Hence, it doesn’t matter whether we declare a variable at the top or anywhere else. This functionality which moves the declaration to the top either inside a function or in the global code is known as hoisting.

out = 2;
var out;
function myfunc() {
var in = "inside"
// some code
// ...
JavaScript will interpret the above in the following manner.
var out;
out = 2;
function myfunc() {
var in;
// some code
in = "inside";

116. How Will You Replace All Occurrences Of A String In JavaScript?


We can use String’s <replace()> method to substitute any string. There are following two ways to use this method.
Pass The Input String As A Regular Expression.

str = "ghktestlllltest-sdds"
str = str.replace(/test/g, '');
Use RegExp Class To Create A Regular Expression And Pass It.
String.prototype.replaceAll = function(find, replace) {
var target = this;
return target.replace(new RegExp(find, 'g'), replace);
str = "ghktestlllltest-sdds"
str = str.replaceAll('test', '');

117. When would you use var in your declaration and when you wouldn’t?


Always use var. Not using var for variable declaration will traverse scopes all the way up till the global scope. If variable with that name is not found it will declare it in the global scope. Therefore not using var implicitly declares variable in the global scope (which, let me remind you, is a bad practice).

(function() {
baz = 5;
var bar = 10;
console.log(baz); // outputs 5
//console.log(bar); // error: bar is not defined

A common mistake is to not use var in loops (e.g. for(i=0; i>10; i++) when i has not been previously declared) which will pollute the global scope and in some cases might bear unexpected results.

118. What does the attribute defer/async do when added to the script tag?


The defer attribute will cause browser to execute script after the document has been parsed. This attribute was first implemented in Internet Explorer 4, then added to HTML 4 and more recentlyHTML 5 spec. You might not have heard of it as it has not been supported by other browsers (Firefox support came in version 3.5 – Gecko 1.9.2). Async is another attribute that can affect how a script is loaded and executed, here is a quote from HTML 5 spec on how this is expected to work:
There are three possible modes that can be selected using these attributes. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the deferattribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.
Note: A somewhat (but not exactly) similar defer behavior can be achieved by placing your script tags at the end of the body tag and that’s what is considered to be modern ‘best practice’

119. What is the difference between == and ===? Which one would you use?


The equality (==) operator will compare for equality after doing necessary type casting, the identity operator (===) doesn’t do any conversions. A good practice suggested by Douglas Crockford is to always use strict equality, couple of examples from Douglas’ book JavaScript: The Good Parts

'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true

120. How would you check if a variable is null/undefined?


//check if bar is null
bar === null
//check if bar is undefined
typeof bar === "undefined"


121. How do you check if a variable is an object


You can use typeof to determine if variable is an object, however bear in mind that null is actually an object! However null object is ‘falsy’ thus the following will work:

if(bar && typeof bar === "object") {
console.log('bar is object and is not null');

122. Discuss scoping in JavaScript.


JavaScript has lexical scoping based on functions but not blocks. Therefore:

//global scope
(function() {
//anonymous function scope
var foo = 1;
function bar() {
//bar function scope
var foo = 2;
console.log(foo); //outputs 1
if(true) {
var foo = 3; //redeclares foo
console.log(foo); //outputs 3

123. Explain hoisting in JavaScript.


As some might not be familiar with the term ‘hoisting’ yet have the relevant experience this question could be asked indirectly
In JavaScript function declarations ( function foo() {} ) and variable declarations ( var bar ) are ‘hoisted’ i.e. are silently moved to the very top of the scope. Consider the following code:

(function() {
console.log(bar); //returns 'undefined'
//console.log(baz) // error: baz is not defined
foo(); // outputs 'aloha' to the console

//function declaration AND its body is hoisted
function foo() {
//variable declaration is hoisted but value assignment stays here
var bar = 1;
baz = 2; //defines baz in global scope

124. What are closures?


(function() {
function foo(x) {
var baz = 3;
return function (y) {
console.log(x + y + (++baz));
var moo = foo(2); // moo is now a closure.
moo(1); // 7
moo(1); // 8!

The inner function inside foo will close-over the variables of foo before leaving creating a closure.

125. Explain prototypal/differential inheritance


Conceptually this is very simple: A new object can inherit properties of an old object.

(function() {
var genericObject = {
bar : "Hello World",
get_bar : function() {
var customObject = Object.create(genericObject); = "Aloha folks!";
console.log(customObject.get_bar()); //outputs: "Aloha folks"
console.log(customObject.get_bar()); //fallbacks to the prototype's value, outputs: "Hello World"

While JavaScript has always been a prototype-oriented language, tools to work with prototypes were somewhat missing. Object.create used in the code snipped above has been added in ECMAScript 5 and has not been supported prior to Firefox 4, Chrome 5, IE 9

126. What is Strict Mode in JavaScript


Strict Mode has been introduced as part of ECMAScript 5 and introduces new, restricted variant of JavaScript which has following aims:
Throws errors for actions that are rather silly but previously didn’t throw an error
Throws errors for potentially unsafe actions
Disables functions that are poorly thought out
Potentially code in strict mode could run faster by eliminating mistakes that would make it difficult for JavaScript engines to perform optimizations
Strict mode can be enabled for the entire source file or on per function basis by adding a string literal “use strict” on top of the file/function i.e.

function foo(){
"use strict";
// ... your code ...