JavaScript Interview Questions and Answers

JavaScript Interview Questions and Answers

1.What are the data types supported by JavaScript?

Ans. The data types supported by JavaScript are:
Undefined
Null
Boolean
String
Symbol
Number
Object

2. What are the features of JavaScript?

Ans. Following are the features of JavaScript:
It is a lightweight, interpreted programming language.
It is designed for creating network-centric applications.
It is an open and cross-platform scripting language.

Q.3.How can you create an object in JavaScript?

Ans. JavaScript supports Object concept very well. You can create an object using the object literal as follows −
var emp = {
name: “Daniel”,
age: 23
};

4.How can you create an Array in JavaScript?

Ans. You can define arrays using the array literal as follows-
var x = [];
var y = [1, 2, 3, 4, 5];

5. How to read a cookie using JavaScript?

Ans. Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie.
The document.cookie string will keep a list of name = value pairs separated by semicolons, where name is the name of a cookie and value is its string value.
You can use strings split() function to break the string into key and values.

6.What is argument objects in JavaScript & how to get the type of arguments passed to a function?

Ans. JavaScript variable arguments represents the arguments that are passed to a function. Using typeof operator, we can get the type of arguments passed to a function. For example −
function func(x){
console.log(typeof x, arguments.length);
}
func(); //==> “undefined”, 0
func(7); //==> “number”, 7
func(“1”, “2”, “3”); //==> “string”, 3

7. How to create a cookie using JavaScript?

Ans. The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this-
document.cookie = “key1 = value1; key2 = value2; expires = date”;

8. What is NaN in JavaScript?

Ans. NaN is a short form of Not a Number. Since NaN always compares unequal to any number, including NaN, it is usually used to indicate an error condition for a function that should return a valid number. When a string or something else is being converted into a number and that cannot be done, then we get to see NaN.

9. How to delete a cookie using JavaScript?

Ans. If you want to delete a cookie so that subsequent attempts to read the cookie return nothing, you just need to set the expiration date to a time in the past. You should define the cookie path to ensure that you delete the right cookie. Some browsers will not let you delete a cookie if you don’t specify the path.

10. What is the difference between Local storage & Session storage?

Ans. Local Storage – The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) – reducing the amount of traffic between client and server. It will stay until it is manually cleared through settings or program.
Session Storage – It is similar to local storage ; the only difference is while data stored in local storage has no expiration time, data stored in session storage gets cleared when the page session ends. Session Storage will leave when the browser is closed.

11.What is Closure?

Ans. Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope. It gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created. To use a closure, simply define a function inside another function and expose it.

12.What will the following code output and why?

var b = 1;
function outer(){
var b = 2
function inner(){
b++;
var b = 3;
console.log(b)
}
inner();
}
outer();

Ans.Output to the console will be “3”.There are three closures in the example, each with it’s own var b declaration. When a variable is invoked closures will be checked in order from local to global until an instance is found. Since the inner closure has a b variable of its own, that is what will be output.Furthermore, due to hoisting the code in inner will be interpreted as follows:

function inner () {
var b; // b is undefined
b++; // b is NaN
b = 3; // b is 3
console.log(b); // output “3”
}

13.Create a function that, given a DOM Element on the page, will visit the element itself and all of its descendents (not just its immediate children).
For each element visited, the function should pass that element to a provided callback function.
The arguments to the function should be:
a DOM element
a callback function (that takes a DOM element as its argument)

Ans.Visiting all elements in a tree (DOM) is a classic Depth-First-Search algorithm application. Here’s an example solution:

function Traverse(p_element,p_callback) {
p_callback(p_element);
var list = p_element.children;
for (var i = 0; i < list.length; i++) {
Traverse(list[i],p_callback); // recursive call
}
}

14.How do you add an element at the begining of an array? How do you add one at the end?

Ans.

var myArray = [‘a’, ‘b’, ‘c’, ‘d’];
myArray.push(‘end’);
myArray.unshift(‘start’);
console.log(myArray); // [“start”, “a”, “b”, “c”, “d”, “end”]

With ES6, one can use the spread operator:

myArray = [‘start’, …myArray];
myArray = […myArray, ‘end’];

Or, in short:

myArray = [‘start’, …myArray, ‘end’];

15. What Is The Prototype Property In JavaScript?

Ans.
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’

16. What is an event bubbling in JavaScript?

Ans.
Event bubbling is a way of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. The execution starts from that event and goes to its parent element. Then the execution passes to its parent element and so on till the body element.

17. What are Exports & Imports?

Ans.
Imports and exports help us to write modular JavaScript code. Using Imports and exports we can split our code into multiple files. For example-

//—— lib.js ——
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}//—— main.js ——
{ square, diag } from ‘lib’;
console.log(square(5)); // 25
console.log(diag(4, 3)); // 5

18. What are escape characters in JavaScript?

Ans. JavaScript escape characters enable you to write special characters without breaking your application. 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.
For example-

document.write “I am a “good” boy”
document.write “I am a “good” boy”

19. What is a prompt box in JavaScript?

Ans. A prompt box is a box which allows the user to enter input by providing a text box. The prompt() method displays a dialog box that prompts the visitor for input. A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input value.

20. What is the difference between Call & Apply

Ans. The call() method calls a function with a given this value and arguments provided individually.
Syntax-
fun.call(thisArg[, arg1[, arg2[, …]]])

The apply() method calls a function with a given this value, and arguments provided as an array.
Syntax-
fun.apply(thisArg, [argsArray])
Q.21. How can you convert the string of any base to integer in JavaScript?
A.The parseInt() function is used to convert numbers between different bases. It takes the string to be converted as its first parameter, and the second parameter is the base of the given string.
For example-

parseInt(“4F”, 16)

21. How can you convert the string of any base to integer in JavaScript?

Ans. The parseInt() function is used to convert numbers between different bases. It takes the string to be converted as its first parameter, and the second parameter is the base of the given string.
For example-

parseInt(“4F”, 16)

22. What is the ‘Strict’ mode in JavaScript and how can it be enabled?

Ans.Strict mode is a way to introduce better error-checking into your code.
When you use strict mode, you cannot use implicitly declared variables, or assign a value to a read-only property, or add a property to an object that is not extensible.
You can enable strict mode by adding “use strict” at the beginning of a file, a program, or a function.

23. List some of the advantages of JavaScript.

Ans. Some of the advantages of JavaScript are:
Server interaction is less
Feedback to the visitors is immediate
Interactivity is high
Interfaces are richer

24. List some of the disadvantages of JavaScript.

Ans. Some of the disadvantages of JavaScript are:
No support for multithreading
No support for multiprocessing
Reading and writing of files is not allowed
No support for networking applications.

25. Define anonymous function

Ans. It is a function that has no name. These functions are declared dynamically at runtime using the function operator instead of the function declaration. The function operator is more flexible than a function declaration. It can be easily used in the place of an expression. For example:

var display=function()
{
alert(“Anonymous Function is invoked”);
}
display();

26. What is DOM? What is the use of document object?

Ans. DOM stands for Document Object Model. A document object represents the HTML document. It can be used to access and change the content of HTML.

27. What is the use of history object?

Ans. The history object of a browser can be used to switch to history pages such as back and forward from the current page or another page. There are three methods of history object.
history.back() – It loads the previous page.
history.forward() – It loads the next page.
history.go(number) – The number may be positive for forward, negative for backward. It loads the given page number.

28. How to write a comment in JavaScript?

Ans. There are two types of comments in JavaScript.
Single Line Comment: It is represented by // (double forward slash)
Multi-Line Comment: Slash represents it with asterisk symbol as /* write comment here */

29. What is the difference between == and ===?

Ans. The == operator checks equality only whereas === checks equality, and data type, i.e., a value must be of the same type.

31. Difference between Client side JavaScript and Server side JavaScript?

Ans. Client-side JavaScript comprises the basic language and predefined objects which are relevant to running JavaScript in a browser. The client-side JavaScript is embedded directly by in the HTML pages. The browser interprets this script at runtime.Server-side JavaScript also resembles client-side JavaScript. It has a relevant JavaScript which is to run in a server. The server-side JavaScript are deployed only after compilation.

32. In which location cookies are stored on the hard disk?

Ans. The storage of cookies on the hard disk depends on the OS and the browser. The Netscape Navigator on Windows uses a cookies.txt file that contains all the cookies. The path is c:Program FilesNetscapeUsersusernamecookies.txt
The Internet Explorer stores the cookies on a file username@website.txt. The path is: c:WindowsCookiesusername@Website.txt.

33. Are Java and JavaScript same?

Ans. No, Java and JavaScript are the two different languages. Java is a robust, secured and object-oriented programming language whereas JavaScript is a client-side scripting language with some limitations.

34. What are the pop-up boxes available in JavaScript?

Ans.
Alert Box
Confirm Box
Prompt Box

35. How can we detect OS of the client machine using JavaScript?

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

36. What is The Viewport?

Ans. The viewport is the user’s visible area of a web page.The viewport varies with the device, and will be smaller on a mobile phone than on a computer screen.Before tablets and mobile phones, web pages were designed only for computer screens, and it was common for web pages to have a static design and a fixed size.Then, when we started surfing the internet using tablets and mobile phones, fixed size web pages were too large to fit the viewport. To fix this, browsers on those devices scaled down the entire web page to fit the screen.

37. What is document.write

Ans. The write() method writes HTML expressions or JavaScript code to a document.The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.

1.What are the data types supported by JavaScript?

Ans. The data types supported by JavaScript are:
Undefined
Null
Boolean
String
Symbol
Number
Object

2. What are the features of JavaScript?

Ans. Following are the features of JavaScript:
It is a lightweight, interpreted programming language.
It is designed for creating network-centric applications.
It is an open and cross-platform scripting language.

Q.3.How can you create an object in JavaScript?

Ans. JavaScript supports Object concept very well. You can create an object using the object literal as follows −
var emp = {
name: “Daniel”,
age: 23
};

4.How can you create an Array in JavaScript?

Ans. You can define arrays using the array literal as follows-
var x = [];
var y = [1, 2, 3, 4, 5];

5. How to read a cookie using JavaScript?

Ans. Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie.
The document.cookie string will keep a list of name = value pairs separated by semicolons, where name is the name of a cookie and value is its string value.
You can use strings split() function to break the string into key and values.

6.What is argument objects in JavaScript & how to get the type of arguments passed to a function?

Ans. JavaScript variable arguments represents the arguments that are passed to a function. Using typeof operator, we can get the type of arguments passed to a function. For example −
function func(x){
console.log(typeof x, arguments.length);
}
func(); //==> “undefined”, 0
func(7); //==> “number”, 7
func(“1”, “2”, “3”); //==> “string”, 3

7. How to create a cookie using JavaScript?

Ans. The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this-
document.cookie = “key1 = value1; key2 = value2; expires = date”;

8. What is NaN in JavaScript?

Ans. NaN is a short form of Not a Number. Since NaN always compares unequal to any number, including NaN, it is usually used to indicate an error condition for a function that should return a valid number. When a string or something else is being converted into a number and that cannot be done, then we get to see NaN.

9. How to delete a cookie using JavaScript?

Ans. If you want to delete a cookie so that subsequent attempts to read the cookie return nothing, you just need to set the expiration date to a time in the past. You should define the cookie path to ensure that you delete the right cookie. Some browsers will not let you delete a cookie if you don’t specify the path.

10. What is the difference between Local storage & Session storage?

Ans. Local Storage – The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) – reducing the amount of traffic between client and server. It will stay until it is manually cleared through settings or program.
Session Storage – It is similar to local storage ; the only difference is while data stored in local storage has no expiration time, data stored in session storage gets cleared when the page session ends. Session Storage will leave when the browser is closed.

11.What is Closure?

Ans. Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope. It gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created. To use a closure, simply define a function inside another function and expose it.

12.What will the following code output and why?

var b = 1;
function outer(){
var b = 2
function inner(){
b++;
var b = 3;
console.log(b)
}
inner();
}
outer();

Ans.Output to the console will be “3”.There are three closures in the example, each with it’s own var b declaration. When a variable is invoked closures will be checked in order from local to global until an instance is found. Since the inner closure has a b variable of its own, that is what will be output.Furthermore, due to hoisting the code in inner will be interpreted as follows:

function inner () {
var b; // b is undefined
b++; // b is NaN
b = 3; // b is 3
console.log(b); // output “3”
}

13.Create a function that, given a DOM Element on the page, will visit the element itself and all of its descendents (not just its immediate children).
For each element visited, the function should pass that element to a provided callback function.
The arguments to the function should be:
a DOM element
a callback function (that takes a DOM element as its argument)

Ans.Visiting all elements in a tree (DOM) is a classic Depth-First-Search algorithm application. Here’s an example solution:

function Traverse(p_element,p_callback) {
p_callback(p_element);
var list = p_element.children;
for (var i = 0; i < list.length; i++) {
Traverse(list[i],p_callback); // recursive call
}
}

14.How do you add an element at the begining of an array? How do you add one at the end?

Ans.

var myArray = [‘a’, ‘b’, ‘c’, ‘d’];
myArray.push(‘end’);
myArray.unshift(‘start’);
console.log(myArray); // [“start”, “a”, “b”, “c”, “d”, “end”]

With ES6, one can use the spread operator:

myArray = [‘start’, …myArray];
myArray = […myArray, ‘end’];

Or, in short:

myArray = [‘start’, …myArray, ‘end’];

15. What Is The Prototype Property In JavaScript?

Ans.
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’

16. What is an event bubbling in JavaScript?

Ans.
Event bubbling is a way of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. The execution starts from that event and goes to its parent element. Then the execution passes to its parent element and so on till the body element.

17. What are Exports & Imports?

Ans.
Imports and exports help us to write modular JavaScript code. Using Imports and exports we can split our code into multiple files. For example-

//—— lib.js ——
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}//—— main.js ——
{ square, diag } from ‘lib’;
console.log(square(5)); // 25
console.log(diag(4, 3)); // 5

18. What are escape characters in JavaScript?

Ans. JavaScript escape characters enable you to write special characters without breaking your application. 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.
For example-

document.write “I am a “good” boy”
document.write “I am a “good” boy”

19. What is a prompt box in JavaScript?

Ans. A prompt box is a box which allows the user to enter input by providing a text box. The prompt() method displays a dialog box that prompts the visitor for input. A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering an input value.

20. What is the difference between Call & Apply

Ans. The call() method calls a function with a given this value and arguments provided individually.
Syntax-
fun.call(thisArg[, arg1[, arg2[, …]]])

The apply() method calls a function with a given this value, and arguments provided as an array.
Syntax-
fun.apply(thisArg, [argsArray])
Q.21. How can you convert the string of any base to integer in JavaScript?
A.The parseInt() function is used to convert numbers between different bases. It takes the string to be converted as its first parameter, and the second parameter is the base of the given string.
For example-

parseInt(“4F”, 16)

21. How can you convert the string of any base to integer in JavaScript?

Ans. The parseInt() function is used to convert numbers between different bases. It takes the string to be converted as its first parameter, and the second parameter is the base of the given string.
For example-

parseInt(“4F”, 16)

22. What is the ‘Strict’ mode in JavaScript and how can it be enabled?

Ans.Strict mode is a way to introduce better error-checking into your code.
When you use strict mode, you cannot use implicitly declared variables, or assign a value to a read-only property, or add a property to an object that is not extensible.
You can enable strict mode by adding “use strict” at the beginning of a file, a program, or a function.

23. List some of the advantages of JavaScript.

Ans. Some of the advantages of JavaScript are:
Server interaction is less
Feedback to the visitors is immediate
Interactivity is high
Interfaces are richer

24. List some of the disadvantages of JavaScript.

Ans. Some of the disadvantages of JavaScript are:
No support for multithreading
No support for multiprocessing
Reading and writing of files is not allowed
No support for networking applications.

25. Define anonymous function

Ans. It is a function that has no name. These functions are declared dynamically at runtime using the function operator instead of the function declaration. The function operator is more flexible than a function declaration. It can be easily used in the place of an expression. For example:

var display=function()
{
alert(“Anonymous Function is invoked”);
}
display();

26. What is DOM? What is the use of document object?

Ans. DOM stands for Document Object Model. A document object represents the HTML document. It can be used to access and change the content of HTML.

27. What is the use of history object?

Ans. The history object of a browser can be used to switch to history pages such as back and forward from the current page or another page. There are three methods of history object.
history.back() – It loads the previous page.
history.forward() – It loads the next page.
history.go(number) – The number may be positive for forward, negative for backward. It loads the given page number.

28. How to write a comment in JavaScript?

Ans. There are two types of comments in JavaScript.
Single Line Comment: It is represented by // (double forward slash)
Multi-Line Comment: Slash represents it with asterisk symbol as /* write comment here */

29. What is the difference between == and ===?

Ans. The == operator checks equality only whereas === checks equality, and data type, i.e., a value must be of the same type.

31. Difference between Client side JavaScript and Server side JavaScript?

Ans. Client-side JavaScript comprises the basic language and predefined objects which are relevant to running JavaScript in a browser. The client-side JavaScript is embedded directly by in the HTML pages. The browser interprets this script at runtime.Server-side JavaScript also resembles client-side JavaScript. It has a relevant JavaScript which is to run in a server. The server-side JavaScript are deployed only after compilation.

32. In which location cookies are stored on the hard disk?

Ans. The storage of cookies on the hard disk depends on the OS and the browser. The Netscape Navigator on Windows uses a cookies.txt file that contains all the cookies. The path is c:Program FilesNetscapeUsersusernamecookies.txt
The Internet Explorer stores the cookies on a file username@website.txt. The path is: c:WindowsCookiesusername@Website.txt.

33. Are Java and JavaScript same?

Ans. No, Java and JavaScript are the two different languages. Java is a robust, secured and object-oriented programming language whereas JavaScript is a client-side scripting language with some limitations.

34. What are the pop-up boxes available in JavaScript?

Ans.
Alert Box
Confirm Box
Prompt Box

35. How can we detect OS of the client machine using JavaScript?

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

36. What is The Viewport?

Ans. The viewport is the user’s visible area of a web page.The viewport varies with the device, and will be smaller on a mobile phone than on a computer screen.Before tablets and mobile phones, web pages were designed only for computer screens, and it was common for web pages to have a static design and a fixed size.Then, when we started surfing the internet using tablets and mobile phones, fixed size web pages were too large to fit the viewport. To fix this, browsers on those devices scaled down the entire web page to fit the screen.

37. What is document.write

Ans. The write() method writes HTML expressions or JavaScript code to a document.The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.