Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18K views

Jaquery Javascript

JavaScript is a client-side scripting language that can be inserted into HTML pages and is understood by web browsers. It is an object-based programming language that is faster than server-side languages like ASP since it does not require web server processing. Some key data types in JavaScript include Number, String, Boolean, Object, and Undefined.

Uploaded by

Edukondalu Morla
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18K views

Jaquery Javascript

JavaScript is a client-side scripting language that can be inserted into HTML pages and is understood by web browsers. It is an object-based programming language that is faster than server-side languages like ASP since it does not require web server processing. Some key data types in JavaScript include Number, String, Boolean, Object, and Undefined.

Uploaded by

Edukondalu Morla
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 128

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

Example:

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.

Example:

var x=1, y=2,


z=
x+y;

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?

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

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.

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.

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

Line

Comment

*/

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();

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

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

Sponsored by Simplilearn

Data Scientists demand will rise by 28% - IBM


Enroll for this acclaimed PGP in Data Science, in partnership
with Purdue University, and fast track your career
See More

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

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 delete keyword is used to delete the property as well as its value.

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

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:

<script language="JavaScript" type="text/javascript" >

<!-- location.href="http://newhost/newpath/newfile.html"; //--></script>

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.

Example:

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.

Example:

var cloths = ["Shirt", "Pant", "TShirt"];


cloths.pop();

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

Try{
Code
}
Catch(exp){
Code to throw an exception
}
Finally{
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;
i="john";

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;

or

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 -

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

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

console.log(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

greet(message);

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() {

console.log(message);

};

// Generate the closure

var JamesGreeter = greeter("James", 23);

// Use the closure

JamesGreeter();

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');
};
anon();

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 '<Foo>'
var someOtherObject = {

myProperty : 'Bar'

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

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

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" );
console.log(name);

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:

<script>
document.write(escape("Hello? How are you!"));
</script>

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:

<script>
document.write(unescape("Hello%3F%20How%20are%20you%21"));
</script>

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.

<script>
var uri="my test.asp?name=ståle&car=saab";

document.write(encodeURI(uri)+ "<br>");

document.write(decodeURI(uri));
</script>

Output -

my%20test.asp?name=st%C3%A5le&car=saab

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 <script> tag.

Add "//-->" without the quotes in the code just before the <script> tag.

Old browsers will now treat this JavaScript code as a long HTML comment.
While, a browser that supports JavaScript, will take the "<!--" and "//-->" as
one-line comments.

Beginner Level JavaScript Interview Questions


Q1. What is the difference between Java & JavaScript?

Java JavaScript

Java is an OOP programming language. JavaScript is an OOP scripting language.


It creates applications that run in a virtual machine or
The code is run on a browser only.
browser.

Java code needs to be compiled. JavaScript code are all in the form of text.

Q2. What is JavaScript?

JavaScript is a lightweight, interpreted programming language with object-oriented


capabilities that allows you to build interactivity into otherwise static HTML pages. The
general-purpose core of the language has been embedded in Netscape, Internet
Explorer, and other web browsers.

Q3. What are the data types supported by JavaScript?

The data types supported by JavaScript are:

 Undefined
 Null
 Boolean
 String
 Symbol
 Number
 Object

Q4. What are the features of JavaScript?


Following are the features of JavaScript:

 It is a lightweight, interpreted programming language.


 It is designed for creating network-centric applications.
 It is complementary to and integrated with Java.
 It is an open and cross-platform scripting language.

Q5. Is JavaScript a case-sensitive language?

Yes, JavaScript is a case sensitive language.  The language keywords, variables,


function names, and any other identifiers must always be typed with a consistent
capitalization of letters.

Q6. What are the advantages of JavaScript?


Following are the advantages of using JavaScript −

 Less server interaction − You can validate user input before sending the page off to
the server. This saves server traffic, which means less load on your server.
 Immediate feedback to the visitors − They don’t have to wait for a page reload to see
if they have forgotten to enter something.
 Increased interactivity − You can create interfaces that react when the user hovers
over them with a mouse or activates them via the keyboard.
 Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.

Q7. How can you create an object in JavaScript?

JavaScript supports Object concept very well. You can create an object using


the object literal as follows −
1 var emp = {

2 name: "Daniel",

3 age: 23

4 };

Q8. How can you create an Array in JavaScript?

You can define arrays using the array literal as follows-

1 var x = [];

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

Q9. What is a name function in JavaScript & how to define it?

A named function declares a name as soon as it is defined. It can be defined


using function keyword as :

1 function named(){

2 // write code here

3 }

Q10. Can you assign an anonymous function to a variable and pass it as


an argument to another function?

Yes! An anonymous function can be assigned to a variable. It can also be passed as an


argument to another function.

Q11. What is argument objects in JavaScript & how to get the type of


arguments passed to a function?

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 −

1 function func(x){

2 console.log(typeof x, arguments.length);

}
3
func(); //==> "undefined", 0
4
5 func(7); //==> "number", 7

6 func("1", "2", "3"); //==> "string", 3

Q12. What are the scopes of a variable in JavaScript?

The scope of a variable is the region of your program in which it is defined. JavaScript


variable will have only two scopes.
• Global Variables − A global variable has global scope which means it is visible
everywhere in your JavaScript code.
• Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.

Q13. What is the purpose of ‘This’ operator in JavaScript?

The JavaScript this keyword refers to the object it belongs to. This has different values
depending on where it is used. In a method, this refers to the owner object and in a
function, this refers to the global object.

Q14. What is Callback?

A callback is a plain JavaScript function passed to some method as an argument or


option. It is a function that is to be executed after another function has finished
executing, hence the name ‘call back‘. In JavaScript, functions are objects. Because of
this, functions can take functions as arguments, and can be returned by other functions.

Q15. What is Closure? Give an example.

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.

Q16. Name some of the built-in methods and the values returned by
them.
Built-in Method Values

CharAt() It returns the character at the specified index.

Concat() It joins two or more strings.

forEach() It calls a function for each element in the array.

It returns the index within the calling String object of t


indexOf()
first occurrence of the specified value.

length() It returns the length of the string.

It removes the last element from an array and return


pop()
that element.

It adds one or more elements to the end of an array a


push()
returns the new length of the array.

reverse() It reverses the order of the elements of an array.

Q17. What are the variable naming conventions in JavaScript?

The following rules are to be followed while naming variables in JavaScript:

1. You should not use any of the JavaScript reserved keyword as variable name. For
example, break or boolean variable names are not valid.
2. JavaScript variable names should not start with a numeral (0-9). They must begin with a
letter or the underscore character. For example, 123name is an invalid variable name
but _123name or name123 is a valid one.
3. JavaScript variable names are case sensitive. For example, Test and test are two
different variables.

Q18. How does TypeOf Operator work?

The typeof operator is used to get the data type of its operand. The operand can be
either a literal or a data structure such as a variable, a function, or an object. It is
a unary operator that is placed before its single operand, which can be of any type. Its
value is a string indicating the data type of the operand.

Q19. How to create a cookie using JavaScript?

The simplest way to create a cookie is to assign a string value to


the document.cookie object, which looks like this-

Syntax :

1 document.cookie = "key1 = value1; key2 = value2; expires = date";


Q20. How to read a cookie using JavaScript?

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.

Q21. How to delete a cookie using JavaScript?

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.

Now let’s move on to the next section of JavaScript interview questions.

Full Stack Web Developer Masters Program

Explore Curriculum

Intermediate Level JavaScript Interview Questions


Q22. What is the difference between Attributes and Property?

Attributes-  provide more details on an element like id, type, value etc.

Property-  is the value assigned to the property like type=”text”, value=’Name’ etc.
Q23. List out the different ways an HTML element can be accessed in a
JavaScript code.

Here are the list of ways an HTML element can be accessed in a Javascript code:
(i) getElementById(‘idname’): Gets an element by its ID name
(ii) getElementsByClass(‘classname’): Gets all the elements that have the given
classname.
(iii) getElementsByTagName(‘tagname’): Gets all the elements that have the given
tag name.
(iv) querySelector(): This function takes css style selector and returns the first selected
element.

Q24. In how many ways a JavaScript code can be involved in an HTML


file?

There are 3 different ways in which a JavaScript code can be involved in an HTML file:

 Inline
 Internal
 External

An inline function is a JavaScript function, which is assigned to a variable created at


runtime. You can differentiate between Inline Functions and Anonymous since an inline
function is assigned to a variable and can be easily reused. When you need a
JavaScript for a function, you can either have the script integrated in the page you are
working on, or you can have it placed in a separate file that you call, when needed. This
is the difference between an internal script and an external script.

Q25. What are the ways to define a variable in JavaScript?

The three possible ways of defining a variable in JavaScript are:

 Var – The JavaScript variables statement is used to declare a variable and, optionally,


we can initialize the value of that variable. Example: var a =10; Variable declarations are
processed before the execution of the code.
 Const – The idea of const functions is not allow them to modify the object on which they
are called. When a function is declared as const, it can be called on any type of object.
 Let – It is a signal that the variable may be reassigned, such as a counter in a loop, or a
value swap in an algorithm. It also signals that the variable will be used only in the block
it’s defined in.

Q26. What is a Typed language?

Typed Language is in which the values are associated with values and not


with variables. It is of two types:
 Dynamically: in this, the variable can hold multiple types; like in JS a variable can take
number, chars.
 Statically: in this, the variable can hold only one type, like in Java a variable declared of
string can take only set of characters and nothing else.
o

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

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.

Q28. What is the difference between the operators ‘==‘ & ‘===‘?

The main difference between “==” and “===” operator is that formerly compares variable
by making type correction e.g. if you compare a number with a string with numeric
literal, == allows that, but === doesn’t allow that, because it not only checks the value
but also type of two variable, if two variables are not of the same type “===” return false,
while “==” return true.

Q29. What is the difference between null & undefined?

Undefined means a variable has been declared but has not yet been assigned a value.
On the other hand, null is an assignment value. It can be assigned to a variable as a
representation of no value. Also, undefined and null are two distinct types: undefined is
a type itself (undefined) while null is an object.

Q30. What is the difference between undeclared & undefined?

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.

Q31. Name some of the JavaScript Frameworks

A JavaScript
framework is an application framework written in JavaScript. It differs from a JavaScript
library in its control flow. There are many JavaScript Frameworks available but some of
the most commonly used frameworks are:

 Angular
 React
 Vue

Q32. What is the difference between window & document in JavaScript?

Window Document

JavaScript window is a global object which holds The document also comes under the window and ca
variables, functions, history, location. be considered as the property of the window.

Q33. What is the difference between innerHTML & innerText?

innerHTML – It will process an HTML tag if found in a string

innerText – It will not process an HTML tag if found in a string

Q34. What is an event bubbling in JavaScript?

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.
Q35. What is NaN in JavaScript?

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.

Q36. How do JavaScript primitive/object types passed in functions?

One of the differences between the two is that Primitive Data Types are passed By
Value and Objects are passed By Reference.

 By Value means creating a COPY of the original. Picture it like twins: they are born
exactly the same, but the first twin doesn’t lose a leg when the second twin loses his in
the war.
  By Reference means creating an ALIAS to the original. When your Mom calls you
“Pumpkin Pie” although your name is Margaret, this doesn’t suddenly give birth to a
clone of yourself: you are still one, but you can be called by these two very different
names.

Q37. How can you convert the string of any base to integer in


JavaScript?

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-

1 parseInt("4F", 16)

Q38. What would be the result of 2+5+”3″?

Since 2 and 5 are integers, they will be added numerically. And since 3 is a string, its
concatenation will be done. So the result would be 73. The ” ” makes all the difference
here and represents 3 as a string and not a number.

Q39. What are Exports & Imports?

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

1 //------ lib.js ------</span>

2 export const sqrt = Math.sqrt;</span>

export function square(x) {</span>


3

4 return x * x;</span>

}
5
export function diag(x, y) {
6
return sqrt(square(x) + square(y));
7
}
8
 
9
//------ main.js ------</span>
10
 { square, diag } from 'lib';
11 console.log(square(5)); // 25

12 console.log(diag(4, 3)); // 5

13

Now with this, we have reached the final section of JavaScript Interview Questions.

Advanced Level JavaScript Interview Questions


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

Strict mode is a way to introduce better error-checking into your code.

Programming & Frameworks Training

JAVA, J2EE & SOA CERTIFICATION TRAINING


Java, J2EE & SOA Certification Training
Reviews

 4(35452)

PYTHON SCRIPTING CERTIFICATION TRAINING


Python Scripting Certification Training
Reviews

 5(7582)
PYTHON DJANGO TRAINING AND CERTIFICATION
Python Django Training and Certification
Reviews

 5(3498)

COMPREHENSIVE JAVA COURSE CERTIFICATION TRAINING


Comprehensive Java Course Certification Training
Reviews

 5(15386)

ADVANCED JAVA CERTIFICATION TRAINING


Advanced Java Certification Training
Reviews

 5(2918)

PHP & MYSQL WITH MVC FRAMEWORKS CERTIFICATION TRAINING


PHP & MySQL with MVC Frameworks Certification Training
Reviews

 5(2545)

SPRING FRAMEWORK CERTIFICATION TRAINING


Spring Framework Certification Training
Reviews
 5(7419)

MICROSOFT .NET FRAMEWORK CERTIFICATION TRAINING


Microsoft .NET Framework Certification Training
Reviews

 5(2657)

NODE.JS CERTIFICATION TRAINING


Node.js Certification Training
Reviews

 5(5476)

Next

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

Q41. What is a prompt box in JavaScript?

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.

Q42. What will be the output of the code below?

1 var Y = 1;

2 if (function F(){})

{
3
y += Typeof F;</span>
4
}
5
console.log(y);
6

The output would be 1undefined. The if condition statement evaluates using eval, so
eval(function f(){}) returns function f(){} (which is true). Therefore, inside the if statement,
executing typeof f returns undefined because the if statement code executes at run
time, and the statement inside the if condition is evaluated during run time.

Q43. What is the difference between Call & Apply?

The call() method calls a function with a given this value and arguments provided
individually.

Syntax-

1 fun.call(thisArg[, arg1[, arg2[, ...]]])

The apply() method calls a function with a given this value, and arguments provided as
an array.

Syntax-

1 fun.apply(thisArg, [argsArray])

Q44. How to empty an Array in JavaScript?

There are a number of methods you can use to empty an array:

Method 1 –

1 arrayList = []

Above code will set the variable arrayList to a new empty array. This is recommended if
you don’t have references to the original array arrayList anywhere else, because it will
actually create a new, empty array. You should be careful with this method of emptying
the array, because if you have referenced this array from another variable, then the
original reference array will remain unchanged.

Method 2 –

1 arrayList.length = 0;

The code above will clear the existing array by setting its length to 0. This way of
emptying the array also updates all the reference variables that point to the original
array. Therefore, this method is useful when you want to update all reference variables
pointing to arrayList.

Method 3 –

1 arrayList.splice(0, arrayList.length);

The implementation above will also work perfectly. This way of emptying the array will
also update all the references to the original array.

Method 4 –

1 while(arrayList.length)

2 {

3 arrayList.pop();

4 }

The implementation above can also empty arrays, but it is usually not recommended to
use this method often.

Q45. What will be the output of the following code?

1
var Output = (function(x)
2 {

3 Delete X;

4 return X;

5 }

)(0);
6
console.log(output);
7

The output would be 0. The delete operator is used to delete properties from an object.
Here x is not an object but a local variable. delete operators don’t affect local variables.

Q46. What will be the output of the following code?

1 var X = { Foo : 1};

2 var Output = (function()

{
3
delete X.foo;
4
return X.foo;
5
}
6
)();
7
console.log(output);
8

The output would be undefined. The delete operator is used to delete the property of an
object. Here, x is an object which has the property foo, and as it is a self-invoking
function, we will delete the foo property from object x. After doing so, when we try to
reference a deleted property foo, the result is undefined.

Q47. What will be the output of the following code?

1 var Employee =

2 {

3 company: 'xyz'

4 }

5 var Emp1 = Object.create(employee);

delete Emp1.company Console.log(emp1.company);


6

The output would be xyz. Here, emp1 object has company as its prototype property.
The delete operator doesn’t delete prototype property. emp1 object doesn’t have
company as its own property. However, we can delete the company property directly
from the Employee object using delete Employee.company.

Q48. What will be the output of the code below? 


Full Stack Web Developer Masters Program

Weekday / Weekend BatchesSee Batch Details

1 //nfe (named function expression)

2 var Foo = Function Bar()

3 {

4 return 7;

5 };

typeof Bar();
6

The output would be Reference Error. A function definition can have only one reference
variable as its function name.

Q49. What is the reason for wrapping the entire content of a JavaScript


source file in a function book?

This is an increasingly common practice, employed by many popular JavaScript


libraries. This technique creates a closure around the entire contents of the file which,
perhaps most importantly, creates a private namespace and thereby helps avoid
potential name clashes between different JavaScript modules and libraries.
Another feature of this technique is to allow for an easy alias for a global variable. This
is often used in jQuery plugins.

Q50. What are escape characters in JavaScript?

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.

1. What is JavaScript(JS)?
 JavaScript is a lightweight, interpreted programming language with object-
oriented capabilities that allows you to build interactivity into otherwise static
HTML pages.

2. What are the features of JavaScript?


 JavaScript is a lightweight, interpreted programming language.
 JavaScript is designed for creating network-centric applications.
 JavaScript is complementary to and integrated with Java.
 JavaScript is complementary to and integrated with HTML.
 JavaScript is open and cross-platform.

 What are the advantages of JavaScript?


 Less server interaction? You can validate user input before sending the page off
to the server.
 Immediate feedback to the visitors? They don’t have to wait for a page reload to
see if they have forgotten to enter something.
 Increased interactivity? You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard

 Why is javascript called Richer Interface?


 You can use JavaScript to include such items as drag-and-drop components and
sliders to give a Rich Interface to your site visitors.

 Is javascript case-sensitive?
 Yes, JavaScript is a case-sensitive language. This means that language keywords,
variables, function names, and any other identifiers must always be typed with a
consistent capitalization of letters.

 How can we create an object in JS?


 var object =
 {
 name: "obj",
 age: 10
 };

 How can we read the properties of an object in js?


 Can write and read properties of an object using the dot(.) notation.

 How to create an array in js and how to read array elements?


 Can you define arrays using the array literal as follows?
 var x = [];
 var y = [1, 2, 3, 4, 5];
 An array has a length property that is useful for iteration. Can we read elements of an array as
follows?
 for (var i = 0; i < x.length; i++)

 How many types of functions JS support?


 A function in JavaScript can be either named or anonymous.

 How to define an anonymous function?


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

 Which built-in method calls a function for each element in the array?
 forEach method calls a function for each element in the array.

 Which type of variable among global and local, takes precedence over other if names are same?
 A local variable takes precedence over a global variable with the same name.

 Difference between “var” and “let” Keywords?


 Var was there from the beginning but the let was introduced in ES2015/ES6.
 Let has block scope and “Var” has function scope

 Difference between “==” and “===” ?


 ” ==” only compares values “===” compare values and type both.

 Difference between “undefine” and “NULL” Keywords?


 When you define a var but not assign any value. typeof(undefine)=> undefine
 Null- manually done. typeof(null)=> object
 What is prototypal Inheritance?
 Every object has a property called a prototype, where we can add methods to it
and when you create another object from these the newly created object will
automatically inherit its parent’s property.

 Which built-in method sorts the elements of an array?


 Sort method sorts the elements of an array.

 Which built-in method reverses the order of the elements of an array?


 Reverse method reverses the order of the elements of an array ?? the first
becomes the last, and the last becomes the first.

 What is SetTimeout()?
 When you setTimeout it becomes asynchronous and it has to wait on the stack
to get everything got finished

 How to add one new element at end of an array in javascript?


 Push method adds one or more elements to the end of an array and returns the
new length of the array.

 What is closure and how do you use it?


 When a function returns the other function the returning function will hold its
environment and this is known as closure.

 Output of below statements


 filter_none
 edit
 play_arrow
 brightness_4
 <script>
 document.write({});
 </script>
 How can you move element in lowercase to uppercase from an array?
 toUpperCase method returns the calling string value converted to upper case.

List of Most Frequently Asked JavaScript Interview Questions


Q #1) What is JavaScript?
Answer: JavaScript is a scripting language developed by Netscape. It can be used to
program web browser or even servers. It can dynamically update the contents of the
webpage, which is the beauty of JavaScript.
Q #2) What are the advantages of using External JavaScript?
Answer: Using External JavaScript in our code has many advantages as stated below.
 Separation of Code is done.
 Code Maintainability is Easy.
 Performance is better.
Q #3) In the following Code snippet can you please predict the output or If you get an
error, please explain the error?
<!DOCTYPE html>

<html>

<body>

<h2> <strong> Sample: Software Testing Help</strong> </h2>

<p id="studentName"></p>

<script>

var studentName = "Sajeesh Sreeni"; // String 'Sajeesh Sreeni' stored in


studentName

var studentName; // varaible is decalred again

document.getElementById("studentName").innerHTML =

"Redeclaring the varaible will not lose the value!.<br>"

+"Here the value in studentName is "+ studentName;


</script>

</body>

</html>

Answer: This code will not produce any errors.


Redeclaration of the variables is allowed in JavaScript. Hence, the value of the variable will
not be lost after the execution of the statement here.

Q #4) In the following Code snippet can you please predict the output or If you get an
error; please explain the error?
<!DOCTYPE html>

<html>

<body>

<h2> <strong> Sample: Software Testing Help</strong> </h2>

<p id="sum_first"></p>

<p id="sum_second"></p>

<script>

var sum_first =50+20+' Sajeesh Sreeni ';

var sum_second= " Sajeesh Sreeni "+50+20;

document.getElementById("sum_first").innerHTML = "The first varaible sum


is :"+sum_first +

"<br>The second varaible sum is :"+sum_second ;

</script>

</body>

</html>
Answer: This code will not show any error!
The output of the code snippet here is:
             The first variable sum is: 70 Sajeesh Sreeni
           The second variable sum is: Sajeesh Sreeni 5020
Q #5) What is the difference between test () and exec () methods?
Answer: Both test () and exec () are RegExp expression methods.
Using test (), we will search a string for a given pattern, if it finds the matching text then it
returns the Boolean value ‘true’ and else it returns ‘false’.

But in exec (), we will search a string for a given pattern, if it finds the matching text then it
returns the pattern itself and else it returns ‘null’ value.

Q #6) What are the Advantages of JavaScript?


Answer: JavaScript Scripting language has many advantages as stated below.
 Lightweight: JavaScript is easy to implement. It has small memory footprints.
 Interpreted: It is an interpreted language. Instructions are executed directly.
 Object-oriented: JavaScript is an object-oriented language.
 First class functions: In JavaScript, a function can be used as a value.
 Scripting Language: It’s a language in which instructions are written for a run-time
environment.
Q #7) In the following Code snippet can you please predict the output or If you get an
error; please explain the error?
<!DOCTYPE html>

<html>

<body>

<h2> <strong> Sample: Software Testing Help</strong> </h2>

<p style='text-decoration:underline'>Example Const Variable </p>

<p id="display"></p>

<script>

const first_num;

first_num =1000;

document.getElementById("display").innerHTML = "First Number:"+ first_num;

</script>
</body>

</html>

Answer: The ‘const’ variable ’first_num’ is not initialized with a value, so the code will
produce a Syntax Error.
The output of the code snippet here is:
Error: Uncaught SyntaxError: Missing initializer in the const declaration
Q #8) Have you used any browser for debugging? If yes, how is it done?
Answer: By, Pressing ‘F12’ key in the keyboard we can enable debugging in the browser.
Chose the ‘Console’ tab to view the result.
In Console, we can set breakpoints and View the value in variables. All the modern
browsers have a built-in debugger with them (For Example: Chrome, Firefox, Opera, and
Safari). This feature can be turned ON and OFF.
Q #9) What is the use of ‘debugger’ keyword in JavaScript code?
Answer: Using the ‘debugger’ keyword in the code is like using breakpoints in the
debugger.
To test the code, the debugger must be enabled for the browser. If debugging is disabled
for the browser, the code will not work. During debugging the code below should stop
executing, before it goes to the next line.

Q #10) What are the distinct types of Error Name Values?


Answer: There are 6 types of values in ‘Error Name’ Property.
Error Description

Range Error We will get this error if we use a number outside the range

Syntax Error This error raises when we use the incorrect syntax. (Please refer Ques No: 7)

Reference Error This error is thrown if used an undeclared variable Please refer Ques No: 19

Eval Error Thrown due to the error in eval(). New JavaScript version doesn’t have this error

Type Error Value is outside the range of types used. Please refer Ques No :22

URI Error Due to the usage of illegal characters.


Q #11) What is JavaScript Hoisting?
Answer: Using ‘JavaScript Hoisting’ method, when an interpreter runs the code, all the
variables are hoisted to the top of the original /current scope. If you have a variable
declared anywhere inside the JavaScript code then it is brought to the top.
This method is only applicable for the declaration of a variable and is not applicable for
initialization of a variable. Functions are also hoisted to the top, whereas function
explanations are not hoisted to the top.

Basically, where we declared the variable inside the code doesn’t matter much.
Q #12) What is JavaScript ‘Strict Mode’?
Answer: ‘Strict mode’ is a restricted variant of JavaScript.
Usually, JavaScript is ‘not very strict’ in throwing errors.

But in ‘Strict mode’ it will throw all types of errors, even the silent errors. Thus, the process
of debugging becomes easier. And the chances for making mistake for the developer is
reduced.

Q #13) What are the characteristics of JavaScript ‘Strict Mode’?


Answer: Given below are the characteristics of JavaScript ‘Strict Mode’:
 ‘Strict Mode’ will stop developers from creating global variables.
 Developers are restricted from using duplicate parameters.
 Strict mode will restrict you from using JavaScript keyword as a variable name or
function name.
 Strict mode is declared with ‘use strict’ keyword at the beginning of the script.
 All browser support strict mode.
Q #14) What are Self Invoking Functions?
Answer: They are also known as ‘Immediately Invoked Function Expressions’ or ‘Self
Executing Anonymous Functions’. These functions are invoked automatically in the code,
hence they are named as ‘Self Invoking Functions’.
Usually, we define a function and invoke it, but if we want to execute a function
automatically where it is explained, and if we are not going to call it again, we can use
anonymous functions. And these types of function have no name.

Q #15) What is the syntax of ‘Self Invoking Function’? Give an example?


Answer:
The syntax for the Self-Invoking function:
(function () {

return () } () ;

Here the last ‘()’ parenthesis in the syntax states that it is a function expression.

Example of Self Invoked Functions:


<!DOCTYPE html>

<html>

<body>

<h2> <strong> Sample: Software Testing Help</strong> </h2>

<p style='text-decoration:underline'>Example for Self-Invoking </p>


<p id="dispaly_num"></p>

<script>

(function (){

elem = document.getElementById("dispaly_num");

elem.innerHTML = "This function has no name.<br>It is called automatically";

}());

</script>

</body>

</html>

Here the anonymous function is automatically invoked in the code snippet.

The function is used to set the text property of <p> tag having ‘display_num’ as Id.

The output of the code snippet here is:


      This function has no name.
     It is called automatically
Q #16) In the following Code snippet, can you please predict the output or If you get
an error; please explain the error?
Answer: 
<!DOCTYPE html>

<html>

<body>

<h2> <strong> Sample : Software Testing Help</strong> </h2>

<p style='text-decoration:underline'>Example for JavaScript Hoisting </p>

<p id="dispaly_num"></p>

<script>
first_num = 100; // Assign value 100 to num

elem = document.getElementById("dispaly_num");

elem.innerHTML = " Here the variable first_num:<u> "+first_num +"</u> is


taken to the top <br>" +

"Since second variable is initialised the value is not taken to the top and it's
value is "

+ "<u>"+second_num +"</u> “;

var first_num; // declaration only

var second_num =200; // Initialised the variable

</script>

</body>

</html>

Please refer previous Ques no: 11, as explained there, the interpreter will take all the
variables declared except initialization to the top.

As per this, ‘first_num’ variable is taken to the top and ‘second_num’ variable is initialized
with a value, so it is not taken to the top. The is code will not throw an error. But the value of
‘second_num’ is undefined.

The output of the code snippet here is:


                Here the variable first_num: 100 is taken to the top
               Since the second variable is initialized the value is not taken to the top and its
value is undefined
Q #17) If you need to hide the JavaScript code from the older browser versions, how
will you perform it?
Answer: In JavaScript Code, after the <script> tag add ‘<! –’ HTML tag.
This will make the browser to not execute the JavaScript code if it was being an older
version of it. Also, after the end </script> tag add ‘//–>’ HTML tag.

This method will help in solving compatibility issues and UI issues to an extent.

<!DOCTYPE html>
<html>

<body>

<h2> <strong> Sample: Software Testing Help</strong> </h2>

<p id="display"></p>

<script> <!--

document.getElementById("display").innerHTML = "Here I am not using an older


version of browser.<br>

So the code will work in my browser";

//-->

</script>

</body>

</html>

Here the code snippet after a <script> tag is executed in my browser as I am not using an
older version of the browser.

The output of the code snippet here is:


         Here I am not using an older version of the browser.
        So the code will work in my browser
Q #18) In the following Code snippet can you please predict the output or If you get
an error, please explain the error?
<!DOCTYPE html>

<html>

<body>

<h2> <strong> Sample: Software Testing Help</strong> </h2>

<p style='text-decoration:underline'>Find the output </p>

<p id="display"></p>
<script>

var first_num =500;

var result= function(){

document.getElementById("display").innerHTML = first_num;

var first_num =1000;

result();

</script>

</body>

</html>

Answer: Here in the code given above, the value of the ‘first_num’ variable will not be
1000.
In JavaScript, there is no hoisting for variable initialization. The function ‘result ()’ will
choose the local variable ‘first_num’, as it is declared inside the function. Since the variable
is declared after it is used, the value of ‘first_num’ is undefined.

The output of the code snippet here is:


Undefined
Q #19) What is the difference between ‘var’ and ‘let’ keyword?
Answer: The Differences are as follows:
Var let

’var’ keyword was introduced in JavaScript code from ‘let’ keyword is introduced in 2015 only.
the beginning Stage itself.

’Var’ keyword has function scope. The variable A variable declared with ‘let’ keyword has a scop
defined with var is available anywhere within the only with in that block. So, let has a Block Scope
function

The variable declared with ‘var’ be hoisted The variable declared with ‘let’ be hoisted
Q #20) In the following Code snippet can you please predict the output or If you get
an error; please explain the error?
<!DOCTYPE html>
<html>

<body>

<h2> <strong> Sample: Software Testing Help</strong> </h2>

<p style='text-decoration:underline'>Find the output </p>

<p id="display_first"></p>

<p id="display_second"></p>

<script>

if(true){

var first_num =1000;

let second_num=500;

document.getElementById("display_first").innerHTML = "First Number:" +


first_num;

document.getElementById("display_second").innerHTML = "Second Number:" +


second_num;

</script>

</body>

</html>

Answer:
The output of the code snippet here is:
First Number :1000
We will get ‘First Number :1000’ as output. There is an ‘Uncaught Reference Error’ error
also. In the code snippet, the scope of ‘second_num’ is only with in the if() block. If a
developer tries to access the value outside the block, he will get a ‘Uncaught Reference
error’.
Uncaught Reference Error: second_num is not defined.
Q #21) What is the difference between ‘==’ and ‘===’?
Answer:
Both ‘==’ and ‘===’ are comparison operators.

‘==’ operator ‘===’ operator

It is known as ‘Type Converting Operator’ It is known as ‘Strict Equality Operator’

It compares Value, do not compare type It compares both value and type.
Q #22) What is the difference between ‘let’ and ‘const’?
Answer :
let const

using ‘let’ we can change the value of variable using ‘const’, after the first assignment of the value w
any number of times cannot redefine the value again

Consider the code Consider the code


{ {
let first_num =1; const second_num =1;
first_num=2; second_num=2;
document. write (first_num); document. write (second_num);
} }
Here the code will give an output, since the Here the code will produce an error, since the
change in value of first_num is possible. ‘second_num’ is assigned with a second value.
Q #23) In the following Code snippet can you please predict the output or If you get
an error; please explain the error?
<!DOCTYPE html>

<html>

<body>

<h2> <strong> Sample: Software Testing Help</strong> </h2>

<p style='text-decoration:underline'>Example of 'Const' Keyword </p>

<p id="display_first"></p>

<p id="display_second"></p>

<script>

let first_num =500;


first_num=501;

document.getElementById("display_first").innerHTML = "First Number:"+


first_num ;

const second_num =1000;

second_num=1001;

document.getElementById("display_second").innerHTML = "Second
Number :"+second_num;

</script>

</body>

</html>

Answer: Please refer Ques No: 21 before reading further


The output of the code snippet is:
            First Number:501
We will also get an Error while running the code, as we are trying to change the value of a
‘const’ variable.

Error: Uncaught TypeError: Assignment to constant variable.


Q #24) What is the difference between ‘null’ and ‘undefined’?
Answer: Both the keywords represent empty values.
The differences are:
 In ‘undefined’, we will define a variable, but we won’t assign a value to that variable.
On the other hand, in ‘null’ we will define a variable and assign the ‘null’ value to the
variable.
 type of (undefined) and type of (null) object.
Q #25) What is the difference between ‘function declaration’ and ‘function
expression’?
Answer:
It can be explained with an Example:
<!DOCTYPE html>

<html>

<body>

<h2> <strong> Sample: Software Testing Help</strong> </h2>


<p style='text-decoration:underline'>Example Function Declaration</p>

<p id="display_add"></p>

<p id="display_sub"></p>

<script>

function add(first_num,second_num){

return first_num + second_num;

var substract = function sub(first_num,second_num){

return first_num - second_num;

var first_num=700;

var second_num=300;

document.getElementById("display_add").innerHTML = "Sum of the number is:"


+ add(first_num,second_num);

document.getElementById("display_sub").innerHTML = "Difference of the


number is:" + substract(first_num,second_num);

</script>

</body>

</html>

As shown in the example add() is a function declaration and subtract() is a function


expression. The syntax of the function declaration is like a function which is saved into a
variable.

Function declarations are hoisted but function expressions are not hoisted.
Q #26) What are ‘settimeout()’?
Answer: (It better to explain this answer with an example)
Consider the code snippet

Console.log (‘First Line’);

Console.log (‘Second Line’);

Console.log (‘Third Line’);

The output of the code snippet here is:


First Line
Second Line
Third Line
Now you introduce the settimeout() method and wrap the same set of code in it.

Settimeout(function() {

Console.log (‘First Line’);

},0);

Console.log (‘Second Line’);

Console.log (‘Third Line’);

The output of the code snippet here is:


Second Line
Third Line
First Line
With the introduction of settimeout(), the processes become asynchronous. The first
statements to be placed in the stack is Console.log (‘Second Line’), and Console.log (‘Third
Line’), and they will get executed first. You need to wait until everything in the stack is
completed first.

Even though ‘0’ is the timeout period, it doesn’t mean that it will be executed right away.

Q #27) What is a Closure and How do you use it?


Answer: A closure is an inner function. It can access the outer variables of a function. In
Closure, within function_1 there is another function_2 which returns ‘A’ value and function_1
also returns a value; say ‘B’.
Here sum() is the outer function and add () is an inner function, it can access all the
variables including ‘first_num’ ‘second_num’ and ‘third_num’. The outer function is calling
the inner function add().
<script>

// To find the sum of two numbers using closure method

function sum( first_num, second_num )

var sumStr= 600;

function add(first_num , second_num)

return (sumStr + (first_num + second_num));

return add();

document.write("Result is :"+ sum(150,350));

</script>

The output of the code snippet here is:


Result is: 500
Q #28) In the following Code snippet can you please predict the output or If you get
an error; please explain the error?
<!DOCTYPE html>

<html>

<body>

<h2> <strong> Sample: Software Testing Help</strong> </h2>

<p style='text-decoration:underline'>Example Assignmnet Statement</p>

<p id="display"></p>
<script>

var x =500;

let y,z,p,q;

q=200;

if(true){

x=y=z=p=q;

document.getElementById("display").innerHTML = "x="+ x + "<br>y :"+ y


+"<br>z :"+ z+"<br>p :"+ p+"<br>q :"+ q;

</script>

</body>

</html>

Answer: The assignment statements are considered from Right to left.


The output of the code snippet here is:
x=200
y:200
z:200
p:200
q:200
Q #29) Can you give an example where the code snippet shows the difference
between test () and exec () methods?
<!DOCTYPE html>

<html>

<body>

<h2> <strong> Sample : Software Testing Help</strong> </h2>


<p style='text-decoration:underline'>Example for exec() methods </p>

<p>Click the button to search for a pattern "How“ in the given string "Hello.
Good Morning. How do you feel today?"</p>

<p>If the "How" is found, the method will return the pattern </p>

<button onclick="searchTxt()">Search</button>

<p id="result"></p>

<script>

function searchTxt() {

var str = "Hello. Good Morning. How do you feel today?";

var search_patt = new RegExp("How");

var res = search_patt.exec(str);

document.getElementById("result").innerHTML ="Found the pattern :"+ res;

</script>

</body>

</html>

Answer: This is an example of the test () and exec () method, Refer Ques No: 5 for more
details.
The output of the code snippet here is:
Found the pattern using exec (): How
Using test () the result is: true
Q #30) Can you give an example showing JavaScript Hoisting?
Answer:
<!DOCTYPE html>

<html>
<body>

<h2> <strong> Sample: Software Testing Help</strong> </h2>

<p style='text-decoration:underline'>Example for JavaScript Hoisting </p>

<p id="dispaly_num"></p>

<script>

num = 100; // Assign value 100 to num

elem = document.getElementById("dispaly_num");

elem.innerHTML = "Here the variables are used before declaring it." +

" <br>The value of the variable is " + num;

var num; // Declare the varaible </script>

</body>

</html>

Please refer Ques No:11 for more details

Here the variable ‘num’ is used before declaring it. But JavaScript Hoisting will allow it.

The output of the code snippet here is:


              Here the variables are used before declaring it.
The value of the variable is 100
Q #31) Can you give an example showing the use of the ‘debugger’ keyword in the
JavaScript code?
Answer:
<!DOCTYPE html>

<html>

<head>

</head>
<body>

<h2> <strong> Sample: Software Testing Help</strong> </h2>

<p style='text-decoration:underline'> Example for debug keyword </p>

<p> Here to test the code, debugger must be enabled for the browser,

<br>during debugging the code below should stop executing before it goes to
the next line. </p>

<p id="wait_result"></p>

<p id="show_result"></p>

<script>

var a = 1000;

var b = 500;

var sum = a + b;

document.getElementById("wait_result").innerHTML = "Adding
numbers......<br>

Select 'Resume Script execution' to continue: ";

debugger;

document.getElementById("show_result").innerHTML = "Sum of the numbers :


"+sum;

</script>

</body>

</html>

Note: The debugger must be enabled for the browser to test the code. Refer Ques No: 5 for
more details
This is an example of debugging keyword (Browser used: Chrome)
The output of the code snippet here is:
Here to test the code, the debugger must be enabled for the browser,
during debugging the code below should stop executing before it goes to the next line.
Adding numbers…
Select ‘Resume Script execution' to continue:
<Click on ‘Resume Script execution’ Button>
Sum of the numbers: 1500
Q #32) In the following Code snippet can you please predict the output or If you get
an error; please explain the error?
<!DOCTYPE html>

<html>

<body>

<h2> <strong> Sample: Software Testing Help</strong> </h2>

<p style='text-decoration:underline'>Example Type Converting </p>

<p id="display"></p>

<script>

var first_num =500;

var first_name='500';

if(first_num == first_name){

document.getElementById("display").innerHTML = "Comparison will return 'true'


by Type converting Operator ";

</script>

</body>

</html>

Answer: Consider the code


If (‘100’==100) {
document. write (“It’s a Type Converting Operator”);

Here

  typeof(‘100’) is string

   typeof(100) is number

the ‘==’ operator will convert the number type, which is on the right side of the
operator to string and compare both values

The output of the code snippet here is:


Comparison will return ‘true' by Type converting Operator
Q #33) Are Java and JavaScript similar? If not, then what is the difference between
Java & JavaScript?
Answer:
Sl
Java JavaScript
No

1 Java is a general-purpose programming JavaScript is a high-level, interpreted scripting languag


language.

2 Java is based on Object-Oriented JavaScript  is both an  object-oriented  as well as a 
Programming (OOPS)concepts. functional  scripting.

3 Runs in a Java Virtual Machine ( JVM ) or Runs on a browser only.


browser.

4 Java code needs to get compiled as Java JavaScript  has no  compilation  step.
class file. Instead, an interpreter in the browser reads over the 
JavaScript code , interprets each line, and runs it.
So, in short, these languages are not at all linked with or dependent on each other.

Q #34) Which data types are supported by JavaScript?


Answer:
JavaScript supports the following Seven primitives data types and Object:
#1) Boolean:
This is a logical data type that can have only two values i.e. true or false.
When we check the data type of ‘true’ or ‘false’ using typeof operator, it returns a boolean.

For Example, typeof(true) // returns boolean


Boolean values can be used for comparing two variables.
For Example,
var x = 2;

var y = 3;

x==y //returns false

Boolean value can also be used to check a condition

For Example,
var x = 2;

var y = 3;

If(x<y){

alert(‘Hi’);

If the above condition ‘x<y’ is true, the alert gets pop up.

Boolean variable can be created using the Boolean() function.

var myvar = ‘Hi';

Boolean(myvar); // This returns true because the 'myvar' value exists

Also, the Boolean object can be created using the new operator as follows:
var myobj = new Boolean(true);

#2) Null:
This is a data type that is represented by only one value, the ‘null’ itself. A null value means
no value.

For Example,
var x = null;

console.log(x);// This returns null

If we check the data type of a using the typeof operator, we get:


typeof(x); // This returns object. type of a null value is an object, not null.

#3) Undefined:
This data type means a variable that is not defined. The variable is declared but it does not
contain any value.

For Example,
var x;

console.log(x); // This returns undefined

x=10;//Assign value to x

console.log(x); // This returns 10

The variable ‘a’ has been declared but hasn’t been assigned a value yet.
We can assign a value to a:

#4) Number:
This data type can be a floating-point value, an integer, an exponential value, a ‘NaN’ or an
‘Infinity’.

For Example,
var x=10; // This is an integer value

var y=10.5; // decimal value

var c = 10e5 // an exponential value

‘xyz’ * 10; //This returns NaN

10/0; // This returns infinity

Number literal can be created by using the Number() function:


var x = Number(10);

console.log(x);// This returns 10

Also, number object can be created using the ‘new’ operator as follows:
var x= new Number(10);

console.log(x); // This returns 10


#5) BigInt:
This is a numeric primitive which can represent integers with arbitrary precision. BigInt is
created by appending n to the end of an integer

For Example,
const x = 15n;

The number can be converted to a BigInt with the BigInt(number) function.


const x = 251;

const y = BigInt(x);

y === 251n // returns true

#6) String:
This data type is used to represent textual data.

For Example,
var strVar1 = “Hi,how are you?”;

var strVar2 = ‘Hi,how are you?’;

New string can also be created using String() function as follows:


var strVar3 = String(‘Hi,how are you?’); // This creates a string literal with value
‘Hi,how are you?’

The String() function is also used to convert a non-string value to a string.


String(150); // This statement will create a string ‘150’

String can also be created using ‘new' operator


var strVar4 = new String(“Hi,how are you?”); // This is a string object

console.log(strVar4); // This will return the string ‘Hi,how are you?’

JavaScript strings are immutable i.e. once a string is created, it can’t be modified. But
another string can be created using an operation on the original string.

For example:
 By concatenating two strings using the concatenation operator (+) or String.concat().
 By getting substring using String.substr().
#7) Symbol:
This is a unique and immutable primitive value and used as the key of an Object property.
Symbols are new to JavaScript in ECMAScript 2015
A Symbol value represents a unique identifier.
For example,
var symVar1 = Symbol("Symbol1");

let symVar2 = Symbol("Symbol1");

console.log(symVar1 === symVar2); // This returns "false".

So, many symbols are created with the same description, they are different values.

Symbols can’t be auto-converted.

For example,
var symVar1 = Symbol("Symbol1");

alert(symVar1); // This gives TypeError: Cannot convert a Symbol value to a


string

This can be worked using toString() as follows:


alert(symVar1.toString()); // Symbol(symVar1), this works

Object data type


An object is a value in memory referenced by an identifier.

Object refers to a data structure having data and instructions to work with the data. Objects
sometimes refer to real-world things, For example, an employee or a car.

For Example,
In JavaScript objects, values are written as name:value pairs as below:
var car1 = {type:"BMW", model:” The BMW X5“, color:"white"};

An object definition can span multiple lines as follows:

var car1 = {

type:"BMW",

model: "The BMW X5",

color:"white"
};

The name:values pairs are called properties. For Example, ‘type’ is property and ‘BMW’ is


the value of the property.
Property values are accessed using objectName.propertyName

or objectName[“propertyName”]

For Example,  car1.type or car1[“type”] , returns ‘BMW’


Value of the object car1 can be changed as follows:

car1.type = “Audi”;

Now,

console.log(car1) ;//This will return {type:"Audi", model:” The BMW X5“ ,


color:"white"};

Q #35) Is JavaScript a case-sensitive language?


Answer: Yes, JavaScript is a case sensitive language. Meaning of this is keywords of the
language, variables, function names, and any other identifiers that must always be typed
with consistent uppercase or lower-case letters.
For Example, myVar is a different variable to myvar.

Q #36) How to determine what data type an operand belongs to?


Answer:  Operand data type can be found using the typeof operator
It returns a string indicating the type of the operand.

Syntax: typeof operand


typeof(operand)

The operand can be any variable, object or function.

For Example,
console.log (typeof 10);// expected output: "number"

console.log (typeof 'hello');// expected output: "string"

console.log (typeof<declared But UndefinedVariable>);//expected


output: //"undefined";

Q #37) Why JavaScript is called as a loosely typed or a dynamic language?


Answer:  JavaScript is called as a loosely typed or a dynamic language because
JavaScript variables are not directly associated with any value type and any variable can be
assigned and re-assigned values of all types:
For Example,
var myvar = ‘abc’; // myvar is string

myvar =true; // myvar is now a boolean

myvar = 10; // myvar is now a number

Q #38) What is null in JavaScript?


Answer: The value null represents the intentional absence of any object value.
This is one of JavaScript's primitive values.

For Example,
Var myvar = null;

console.log(myvar); //This will print null

Q #39) What is NaN?


Answer: NaN is a property of global object representing Not-A-Number.
For Example,
function checkValue(x) {

if (isNaN(x)) {

return NaN;

return x;

console.log(checkValue ('5')); //expected output: "5"

console.log(checkValue (‘Any value’)); //expected output: NaN

Q #40) How to split a string into array items?


Answer: A string can be split into an array using the JavaScript split() method. This method
takes a single parameter, the character you want to separate the string at, and returns the
substrings between the separator as items in an array.
For Example,
myDaysString = ''Sunday,Monday,Tuesday,Wednesday”;

String can be split at comma as below:

myDaysArray= myDaysString.split(',');

console.log(myDaysArray[0]); //output is the first item in the array i.e. Sunday

console.log (myDaysArray[myDaysArray.length-1]); //output is the last //item in


the array i.e. Wednesday

Q #41) How to join array items into a string?


Answer: Array items can be joined using the join() method.
For Example,
var myDaysArray= ["Sunday","Monday","Tuesday",”Wednesday”];

Array items are joined into a string as follows:


myDaysString= myDaysArray.join(',');

console.log(myDaysString);//output is joined string


i.e.//Sunday,Monday,Tuesday,Wednesday

Q #42) What type of errors does JavaScript have?


Answer: Following are the 2 types of error:
Syntax errors: These are typos or errors in spelling in the code which cause the program
not to run at all or stop working partway through. Usually, error messages are also provided.
Logic errors: These are errors when the syntax is correct, but the logic or code is
inaccurate. Here, the program runs successfully without errors. But output results are
incorrect. These are often harder to fix than syntax errors as these programs don’t give any
error messages for logic errors.
Q #43) How to handle a large number of choices for one condition in an
effective way?
Answer: This is done using switch statements:
For Example,
switch (expression) {

case choice1:

code to be run
break;

case choice2:

code to be run

break;

default:

code to run if there is no case match

Q #44) What is a ternary operator?


Answer: The ternary or conditional is an operator that is used to make a quick choice
between two options based on a true or false test.
This can be used as a substitute forif…else block when having two choices that are chosen
between a true/false condition.

For Example,
if (some condition)

result = ‘result 1’;

else

result = ‘result 2’;

Same code can be written using a ternary operator in a single statement as follows:
result = (condition)?‘result 1’:‘result 2’;
Q #45) Suppose, there is an object called a person
const person = {
name : {
first: ‘Bob',
last: ‘Smith'
}
};
Which of the following is correct way of accessing the object property ‘first' ?
 person.name.first
or
 person[‘name'][‘first'] ?
Answer: Both are correct ways. i.e. using dots like person.name.first or using bracket
notation like person[‘name'][‘first']
Q #46) What is “this”?
Answer: The ‘this' keyword refers to the current object the code is being written inside.
This is to ensure that the correct values are used when a member's context changes

For Example, there are two different instances of a person having different names and it is
required to print their own name in the alert as follows:
const person1 = {

name: 'Tom',

greeting: function() {

alert('Good Morning! I am ' + this.name + '.');

Here, output is Good Morning! I am ‘Tom'


const person2 = {

name: 'Jerry',

greeting: function() {

alert('Good Morning! I am ' + this.name + '.');

}
Here, the output is Good Morning! I am ‘Jerry'
Q #47) What are Anonymous functions?
Answer: Anonymous functions are functions without having any name and won't do
anything on their own. These are generally used along with an event handler.
For example, in the following code, anonymous function code i.e. alert(‘Hi'); would run on
click of the associated button:
var myButton = document.querySelector('button');

myButton.onclick = function() {

alert('Hi');

Anonymous function can also be assigned to the value of a variable.

1) Explain what is Javascript?

Javascript
Javascript is an object-oriented computer programming language commonly used to
create interactive effects within web browsers.It is first used by the Netscape browser,
that provides access to the HTML document object model (DOM), provides access to
the browser object model (BOM). Javascript syntax looks a lot like java, c or c++ syntax.

Below is the list of data types supported by Javascript:-

 Undefined
 Null
 Boolean
 String
 Symbol
 Number
 Object

Video Player is loading.


2) What close() does in Javascript?

In Javascript close() method is used to close the current window. You must write
window.close() to ensure that this command is associated with a window object and not
some other JavaScript object.

3) What is the difference between let and var?

Both var and let are used for variable/ method declaration in javascript but the main
difference between let and var is that var is function scoped whereas let is block
scoped.

4) Explain Closures in JavaScript?

Closures are the combination of lexical environment and function within which the
function was declared. This allows JavaScript programmers to write better, more
creative, concise and expressive codes. The closure will consist of all the local variables
that were in-scope when the closure was created.

Sure, closures appear to be complex and beyond the scope, but after you read this
article, closures will be much more easy to understand and more simple for your
everyday JavaScript programming tasks. JavaScript is  a very function-oriented
language it gives the user freedom to use functions as the wish of the programmer.

5) Explain JavaScript Event Delegation Model?

In JavaScript, there is some cool stuff that makes it the best of all. One of them is
Delegation Model. When capturing and bubbling, allow functions to implement one
single handler to many elements at one particular time then that is called event
delegation. Event delegation allows you to add event listeners to one parent instead of
specified nodes. That particular listener analyzes bubbled events to find a match on the
child elements. Many people think it to be complicated but in reality, it is very simple if
one starts understanding it.

Also, Read Five JavaScript Frameworks to learn in 2018


6) Describe negative infinity in JavaScript?

NEGATIVE_INFINITY property represents negative infinity and is a number in


javascript, which is derived by ‘dividing negative number by zero’. It can be better
understood as a number that is lower than any other number. Its properties are as
follows:
– A number of objects need not to be created to access this static property.
– The value of negative infinity is the same as the negative value of the infinity property
of the global object.

The values behave differently than the mathematical infinity:

1. Any positive value, including POSITIVE_INFINITY, multiplied by NEGATIVE_INFINITY


is NEGATIVE_INFINITY.
2. Any negative value, including NEGATIVE_INFINITY, multiplied by NEGATIVE_INFINITY
is POSITIVE_INFINITY.
3. Zero multiplied by NEGATIVE_INFINITY is NaN.
4. NaN multiplied by NEGATIVE_INFINITY is NaN.
5. NEGATIVE_INFINITY, divided by any negative value except NEGATIVE_INFINITY, is
POSITIVE_INFINITY.
6. NEGATIVE_INFINITY, divided by any positive value except POSITIVE_INFINITY, is
NEGATIVE_INFINITY.
7. NEGATIVE_INFINITY, divided by either NEGATIVE_INFINITY or POSITIVE_INFINITY,
is NaN.
8. Any number divided by NEGATIVE_INFINITY is zero.

7) Explain function hoisting in JavaScript?

JavaScript’s default behavior that allows moving declarations to the top is called
Hoisting. The 2 ways of creating functions in JavaScript are Function
Declaration and Function Expression. Let’s find out more about these:

Function Declaration
A function with the specific parameters is known as function declarations. To create a
variable in JavaScript is called declarations.

e.g:

hoisted(); // logs "foo"

function hoisted() {
 console.log('foo');

}
Function Expression

When a function is created by using an expression it is called function expression.

e.g:

notHoisted(); // TypeError: notHoisted is not a function

var notHoisted = function() {

  console.log('bar');

};

8) What is the use of let & const in JavaScript?

In modern javascript let & const are different ways of creating variables. Earlier in
javascript, we use the var keyword for creating variables. let & const keyword is
introduced in version ES6 with the vision of creating two different types of variables in
javascript one is immutable and other is mutable.
const: It is used to create an immutable variable. Immutable variables are variables
whose value is never changed in the complete life cycle of the program.
let: let is used to create a mutable variable. Mutable variables are normal variables like
var that can be changed any number of time.

9) Explain Arrow functions?

An arrow function is a consise and short way to write function expressions in Es6 or
above.A rrow functions cannot be used as constructors and also does not supports this,
arguments, super, or new.target keywords. It is best suited for non-method functions. In
general an arrow function looks like const function_name= ()=>{}

const greet=()=>{console.log('hello');}
greet();

10) What are exports and imports?


Imports and exports help us to write modular javascript code. Using Imports and exports
we can split our code into multiple files. Imports allow taking only some specific
variables or methods of a file. We can import methods or variables that are exported by
a module. See the below example for more detail.

//index.js

import name,age from './person';

console.log(name);
console.log(age);

//person.js

let name ='Sharad', occupation='developer', age =26;

export { name, age};

11) What is difference between module.exports and export?

The module is a plain JavaScript object with an exports property. Exports is a plain
JavaScript variable that happens to be set to module.exports. At the end of your file,
node.js will basically ‘return’ module.exports to the require function. A simplified way to
view a JS file in Node could be this:

var module = { exports: {} };


var exports = module.exports;

// your code
return module.exports;
If you set a property on exports, like exports.a = 9;, that will set module.exports.a as well
because objects are passed around as references in JavaScript, which means that if
you set multiple variables to the same object, they are all the same object; so then
exports and module.exports are the same objects.
But if you set exports to something new, it will no longer be set to module.exports, so
exports and module.exports are no longer the same objects.

Source : https://stackoverflow.com/questions/16383795/difference-between-module-
exports-and-exports-in-the-commonjs-module-system

12) How to import all exports of a file as an object.


import * as object name from ‘./file.js’ is used to import all exported members as an
object. You can simply access the exported variables or methods using dot (.) operator
of the object.

Example:

objectname.member1;
objectname.member2;
objectname.memberfunc();

13) Explain “use strict” ?

“use strict” is a javascript directive that is introduced in Es5. The purpose of using “use
strict” directive is to enforce the code is executed in strict mode. In strict mode we can’t
use a variable without declaring it. “use strict” is ignored by earlier versions of
Javascript.

14) Explain Event bubbling and Event Capturing in JavaScript?

Event Capture and Bubbling: In HTML DOM API there are two ways of event
propagation and determines the order in which event will be received. The two ways are
Event Bubbling and Event Capturing. The first method event bubbling directs the event
to its intended target, and the second is called event capture in which the event goes
down to the element.

Event Capture

The capture procedure is rarely used but when it’s used it proves to be very helpful.
This process is also called ‘trickling’. In this process, the event is captured first by the
outermost element and then propagated to the innermost element. For example:

<div>

<ul>

<li></li>

</ul>

</div>
From the above example, suppose the click event did occur in the ‘li’ element, in that
case capturing event it will be first handled ‘div’, then ‘ul’ and at last the target element
will be hit that is ‘li’

Event Bubbling

Bubbling just works like the bubbles, the event gets handled by the innermost element
and then propagated to the outer element.

<div>
<ul>

<li></li>

</ul>

</div>
From the above example, suppose the click event did occur in the ‘li’ element in
bubbling model the event will be handled first by ‘li’ then by ‘ul’ and at last by ‘div’
element.

15) In Javascript are calculations with fractional numbers guaranteed to


be precise?

NO, calculations with fractional numbers are not guaranteed to be precise in Javascript

16) List the comparison operators supported by Javascript?

Javascript supports below comparison operators

 > Greater than


 < Less than
 <= Less than or equal to
 >= Greater than or equal to
 == Equal to
 != Not Equal to
 === Equal to with datatype check
 !== Not equal to with datatype check
17) How do you declare variables in Javascript?

In Javascript variable are declared using the var keyword.A variable must begin with
A letter, $ or _.

eg. var myVar=”Online Interview Questions”;

PS: All variables in Javascript are Case sensitive.

Also, read Advanced JavaScript Interview Questions

18) What will happen if an infinite while loop is run in Javascript?

The program will crash the browser.

19) List HTML DOM mouse events?

HTML DOM mouse events

 onclick
 ondblclick
 mousemove
 mousedown
 mouseover
 mouseout
 mouseup

20) How to get the last index of a string in Javascript?

string.length-1 is used to get the last index of a string in Javascript

Example Usage:-

var myString="JavascriptQuestions";
console.log(myString.length-1);
21) How to get the primitive value of a string in Javascript?

In Javascript valueOf() method is used to get the primitive value of a string.

Example Usage:

var myVar= "Hi!"


console.log(myVar.valueOf())

22) What are the primitive data types in JavaScript?

A primitive is a basic data type that’s not built out of other data types. It can only
represent one single value. All primitives are built-in data types by necessity, (the
compiler has to know about them,) but not all built-in data types are primitives.

In JavaScript there are 5 primitive data types are available they


are undefined, null, boolean, string and number are available.Everything else in
Javascript is an object.

23) What does the instanceof operator do?

In Javascript instanceof operator checks whether the object is an instance of a class or


not:

Example Usage

Square.prototype = new Square();


console.log(sq instanceof Square); // true

24) What is Javascript BOM?

BOM stands for “Browser Object Modal” that allows Javascript to ‘talk’ to the browser,
no standards, modern browsers implement similar BOMS – window, screen, location,
history, navigator, timing, cookies.

25) What are different types of Popup boxes available in Javascript?


In Javascript there are 3 types of Popup Boxes are available, they are

 Alert
 Confirm
 Prompt

Read 80+ Best Angular Js Interview Questions

26) How can you create an array in Javascript?

There are 3 different ways to create an array in Javascript. They are

 By array literal
usage:

var myArray=[value1,value2...valueN];

 By creating instance of Array


usage:

var myArray=new Array();

 By using an Array constructor


usage:

var myArray=new Array('value1','value2',...,'valueN');

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

Strict mode is a way to introduce better error-checking into your code. When you use
strict mode, you cannot, for example, 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. This kind of declaration is known as a directive prologue. The
scope of a strict mode declaration depends on its context. If it is declared in a global
context (outside the scope of a function), all the code in the program is in strict mode. If
it is declared in a function, all the code in the function is in strict mode.
28) How to calculate Fibonacci numbers in JavaScript?

Calculating Fibonacci series in JavaScript


Fibonacci numbers are a sequence of numbers where each value is the sum of the
previous two, starting with 0 and 1. The first few values are 0, 1, 1, 2, 3, 5, 8, 13 ,…,

function fib(n) {
var a=0, b=1;
for (var i=0; i < n; i++) {
var temp = a+b;
a = b;
b = temp;
}
return a;
}

29) What is the difference between the substr() and substring() functions
in JavaScript?

Difference between the substr() and substring() functions in JavaScript.


The substr() function has the form substr(startIndex,length). It returns the substring from
startIndex and returns ‘length’ number of characters.

var s = "hello";
( s.substr(1,4) == "ello" ) // true
The substring() function has the form substring(startIndex,endIndex). It returns the
substring from startIndex up to endIndex – 1.

var s = "hello";
( s.substring(1,4) == "ell" ) // true

30) What are different types of Inheritence? Which Inheritance is


followed in Javascript.

There are two types of Inherientence in OOPS Classic and Prototypical Inheritance. Javascript
follows Prototypical Inheritance.

31) What is output of undefined * 2 in Javascript?


nan is output of undefined * 2.

32) How to add/remove properties to object dynamically in Javascript?

You can add a property to an object using object.property_name =value, delete


object.property_name is used to delete a property.

Example:

let user = new Object();


// adding a property
user.name='Anil';
user.age =25;
console.log(user);
delete user.age;
console.log(user);

33) How to convert Javascript date to ISO standard?

toISOString() method is used to convert javascript date to ISO standard. It converts


JavaScript Date object into a string, using the ISO standard.

Usage:

var date = new Date();


var n = date.toISOString();
console.log(n);
// YYYY-MM-DDTHH:mm:ss.sssZ

34) How to get inner Html of an element in JavaScript?

InnerHTML property of HTML DOM is used to get inner Html of an element in


JavaScript.

Example Usage:

This is inner Element

<script type="text/javascript">
var inner= document.getElementById("inner").innerHTML ;
console.log(inner); // This is inner Element
document.getElementById("inner").innerHTML = "Html changed!";
var inner= document.getElementById("inner").innerHTML ;
console.log(inner); // Html changed!
</script>

35) How to clone an object in Javascript?

Object.assign() method is used for cloning an object in Javascript.Here is sample usage

var x = {myProp: "value"};


var y = Object.assign({}, x);

36) List different ways of empty an array in Javascript?

In Javascript, there are many ways to empty an array in Javascript, below we have


listed 4 major

 By assigning an empty array.

 var arr1 =[1,4,5,6];


 arr1=[];
 By assigning array length to 0.

 var arr2 =[1,4,5,6];


 arr2.length=0;
 By poping the elements of the array.

 var arr2 =[1,4,5,6];


 while(arr.length > 0) {
 arr.pop();
 }
 By using .splice() .

 var arr =[1,4,5,6];


 arr.splice(0,arr.length)

37) How to get an element by class in JavaScript ?

document.getElementsByClassName() method is used in Javascript to get an


element with a class name.
getElementsByClassName()

Method Name getElementsByClassName

Syntax document.getElementsByClassName('className')

Parameter String (name of class)

Output Array of HTMLCollection that have inputted className

38) Explain Typecasting in Javascript?

In Programming whenever we need to convert a variable from one data type to another
Typecasting is used. In Javascript, we can do this via library functions. There are
basically 3 typecasts are available in Javascript Programming, they are:

 Boolean(value): Casts the inputted value to a Boolean


 Number(value): Casts the inputted value to an Integer or Floating point Number.
 String(value) : Casts the inputted value value a string

39) How to encode and decode a URL in JavaScript?

encodeURI() function is used to encode an URL in Javascript.It takes a url string as


parameter and return encoded string. Note: encodeURI() did not encode characters
like / ? : @ & = + $ #, if you have to encode these characters too please use
encodeURIComponent(). Usage:

var uri = "my profile.php?name=sammer&occupation=pāntiNG";


var encoded_uri = encodeURI(uri);
decodeURI() function is used to decode an URL in Javascript.It takes a encoded url
string as parameter and return decoded string. Usage:

var uri = "my profile.php?name=sammer&occupation=pāntiNG";


var encoded_uri = encodeURI(uri);
decodeURI(encoded_uri);

40) How to you change the title of the page by JavaScript?


You can change the title of a webpage using setting the title property of the document
object.

Example usage

document.title="My New Title";

41) What is difference between deep and shallow object coping in


JavaScript?

Some differences are:

 Deep copy means copies all values or properties recursively in the new object whereas
shallow copy copies only the reference.
 In a deep copy, changes in the new object don't show in original object whereas, in
shallow copy, changes in new objects will reflect in the original object.
 In a deep copy, original objects do not share the same properties with new object
whereas, in shallow copy, they do.

42) List some Unit Testing Frameworks JavaScript

Below is the list of few most Popular Javascript Unit Testing Frameworks:

 Unit.js
 Jasmine
 Karma
 Chai
 AVA
 Mocha
 JSUnit
 QUnit
 Jest

43) How to add a new property in existing function JavaScript?

It is easy to add a new property in existing function by just giving value to the existing
function it. For example, let we have an existing object person, to give new property
check the below code:
person.country= “India”;

The new property “country” has added to the object person.

44) Explain JavaScript Accessors ?

JavaScript Accessors

45) List few difference between primitive and non primitive JavaScript
data types?

 The primitive data types are numbers, strings, Boolean, undefined, null and anything
other than these data types are known as non-primitive such as objects and functions.
 Primitive data types are immutable while non-primitives are mutable.
 Primitives are known immutable as they can't be changed once they created but non-
primitive are changeable, means once an object is created, it can be changed.
 Primitives data types are compared with their values, it means two values are strictly
equal if they have the same data type and holds the same value.
 Non-primitives are not compared with values. For example, if two objects have the same
properties and values, they are strictly not equal.

46) Explain higher-order functions in JavaScript?

Higher order function is the best feature of functional programming available in


JavaScript. It is the function which takes a function as an argument and returns a
function as a result. Some of the inbuilt higher-order functions are mapping, filtering,
reduction, zipping, etc.

47) Explain few difference between null, undefined or undeclared


JavaScript variable?

Null is a value that can be assigned to a variable or an object.


Undefined means a variable has been declared but no value is assigned to it. This type
of variable is declared itself to be undefined.

Undeclared means the variable has declared without any datatype.

Null, Undefined are primitive data types whereas Undeclared is not a primitive data
type.

48) How host objects are different from native objects in JavaScript?

Host objects: These are those objects which environment gives. It means they are
different for different environments. For example, browsers include objects such as
windows but Node.js environments give objects such as Node List.

Native Objects: these are built-in objects in JavaScript. They are also known as Global
Objects because they will be available to you independent of ay environment if you
working in JavaScript.

49) What is difference between var x =1; and x=1;?

  

50) Explain spread operator in JavaScript?

The spread operator expands an expression in places where multiple


argument/variables/elements are needed to present. It represents with three dots (…).

For example:

var mid = [3, 4];

var newarray = [1, 2, ...mid, 5, 6];

console.log(newarray);

// [1, 2, 3, 4, 5, 6]
In above example, instead of appending mid array, it rather expands in the newarray
with the help of spread operator. This is how spread operator works in JavaScript.

51) How to remove duplicates from JavaScript Array?

There are many ways to remove duplicates from JavaScript array. These are described
below with examples:

1. By using Set: It is the simplest approach to remove duplicates. Set is an inbuilt


object to store unique values in an array. Here's how we use set:

function uniquearray(array) {
let unique_array= Array.from(set(array))
return unique_array;}
As in the above code, you created a set of an array which automatically eliminates the
duplicate values.

2. By using Filter: Another approach to remove duplicates from an array is applying


filter on an array. To call filter method, it requires three arguments: array, current
element, index of current element. Here’s how we use filter:

function unque_array (arr){


let unique_array = arr.filter(function(elem, index, self) {
return index == self.indexOf(elem); }
return unique_array }
console.log(unique_array(array_with_duplicates));
3. By using for loop: In this, we can use for loop to remove duplicates. In this we make
an empty array in which those elements will be added from the duplicate array which
are not present in this before. Thus, finally we will get an array which has unique
elements. Code to implement this:

Array dups_names = ['Ron', 'Pal', 'Fred', 'Rongo', 'Ron'];


function dups_array(dups_names) {
let unique = {};
names.forEach(function(i) {
If (!unique[i]) {
unique[i] = true; }
});
return Object.keys(unique);} // Ron, Pal, Fred, Rongo
Dups_array(names);
These are the main three methods used in JavaScript to get a unique array.

52) How to call a function in every x seconds in JavaScript?


In JavaScript, we use the function setInterval() to call any function in every x seconds.

Syntax: setInterval(function, milliseconds, param1, param2, ...)

Function: it is a required parameter which includes the function to be execute.

Milliseconds: required parameter which tells how often the function will execute.

Others are an additional parameter.

For example: setInterval(function (){ alert("Hello"); }, 3000);

In the above example, this function calls hello function in very 3 seconds.

53) Explain Promise in JavaScript?

A promise is an object in JavaScript which is used to produce a value that may give
results in the future. The value can be resolved value or it can be a reason which tells
why the value is not resolved.

A promise can be of three states:

 Fulfilled: The operation is completed and the promise has a specific value.


 Rejected: The operation is failed and promise has a reason which shows why the
operation failed.
 Pending: Th operation is not fulfilled or rejected, which means it has not completed yet.

54) What is difference between Array.splice() and Array.slice() method in


JavaScript?

 The array.slice() removes items from the array and then return those removed items as
an array whereas array.slice() method is selected items from an array and then those
elements as a new array object.
 The splice() method affects the original array whereas slice() method doesn’t affect the
original array.
 Splice() method takes n number of arguments whereas slice() can take only two
arguments.

Syntax of splice(): array.splice(index, howmany, item1, ....., itemX)


Syntax of slice(): array.slice(start, end)

55) Is JavaScript multi-threaded or single-threaded?

JavaScript is single-threaded.

56) Explain JavaScript Debounce Function?

  

57) List some Design patterns in JavaScript?

The design pattern is a general reusable solution to a commonly occurring problem in


software design. Some of the design patterns are:

1. Creational design pattern: These patterns dealt with the mechanism of object creation
which optimize object creation with the basic approach.
2. Structural design pattern: these patterns deal with different classes and objects to
provide new functionality.
3. Behavioral Patterns: These patterns are to improve communication between objects
and to recognize patterns.
4. Concurrency design patterns: These patterns handle with multi-thread programming
paradigms.
5. Architectural design patterns: These patterns used to deal with architectural designs.

58) What is console.time() and console.timeEnd()? What is its syntax,


and why is it used?

  

59) What are different types of Scope Chain available in JavaScript?


If we check in the program, every local scope has a connection with one or more scope
in their back which forms a chain. This chain goes on until it met with the global scope
which is the root of this hierarchy. As global scope doesn't have a parent, so it is on the
top of the chain. This is known as scope chain.

The scope chain in JavaScript is basically used to resolve the values of the variable.
Without this, it is difficult for a JavaScript to choose a certain value for a variable if there
are many variables defined at different scopes.

60) How to remove duplicate values from a JavaScript array?

We can use array.indexOf method to check a value exists or not. See below example to
remove duplicate values.

let duplicates = ['delhi','kanpur','kanpur','goa','delhi','new york'];

function removeDuplicatesValues(arr){
let unique_array = [];
for(let i = 0;i < arr.length; i++){
if(unique_array.indexOf(arr[i]) == -1){
unique_array.push(arr[i])
}
}
return unique_array
}

console.log(removeDuplicatesValues(duplicates));

61) How to redirect a page to another page in Javascript?

There are several ways to redirect page to another page in JavaScript. These are:

1. Using location.href: It is the first approach to redirect page. In this, we can go back to
access the original document. Syntax:window.location.href
=“https://www.onlineinterviewquestions.com/”
2. Using location.replace: Another approach to redirect page. In this, it is not possible to
navigate back to the original document by clicking on the back button as it removes the
URL of the original document. Syntax: window.location.replace("
https://www.onlineinterviewquestions.com/;");

62) Is it possible to do 301 redirects in Javascript ?


JavaScript entirely runs on the client machine. 301 is response code that is sent by the
server as a response. So it is not possible to do 301 Redirects In JavaScript.

63) Write a program to reverse a string in pure JavaScript?

There are many ways to reverse a string in JavaScript. These are:

Using in-built functions: the inbuilt function reverse() reverses the string directly.
Here’ how:

str="jQuery";
str = str.split(""); //convert 'jQuery' to array
str = str.reverse(); //reverse 'jQuery' order
str = str.join(""); //then combines the reverse order values.
alert(str);
First split the string to an array, then reverse an array and after that join the characters
to form a string.

Using a loop: First, count a number of characters in a string, then apply a


decrementing loop on an original string which starts from the last character and prints
each character until count becomes zero.

64) List few Difference between JAVA and JavaScript?

  

65) Explain MUL function in Javascript?

MUL means simple multiplication of numbers. It is a techique in which you pass a one
value as an argument in a function and that function returns another function to which
you pass the second value and the process go on. For example: x*y*z can be
representing as:

function mul (x) {


return function (y) { // anonymous function
return function (z) { // anonymous function
return x * y * z; };
};
}

66) List few advantages of using JavaScript?

Few advantage og Javascript

 Javascript is executed on user's computer, the meaning is that whatever you do in


Javascript will not add any processing strain on the server. and that's why it is called as
the client-side programming language. And this feature makes your sites responsive for
the end user and less expensive for you in terms of server traffic.
 With the help of Javascript, you can create highly responsive interfaces which will
improve the user experience and provide dynamic functionality, without waiting for the
server to show another page.
 If you want to make online systems available offline and sync automatically once the
computer goes online, then Javascript is the best technology you can use. you can do
this using the right browser add-ons (Such as Google or Yahoo Browser Plus).
 Content loading and changing it dynamically. Using Ajax in Javascript you can load
content into the document if and when the user needs it, without reloading the entire
page.
 Using the Principles of unobtrusive JavaScript(defensive Scripting), JavaScript can test
for what is possible in your browser and react accordingly.

67) What is use of settimeout function in JavaScript?

  

68) What is difference between local and global scope in JavaScript ?

  

69) What are anonymous functions in JavaScript ?

  
70) Please explain equality operators in JavaScript?

    

71) What are the different types of errors available in JavaScript?

There are three types of errors available in JavaScript

 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 a different operation.

Q:- What is JavaScript?


JavaScript(JS) is an object-based, lightweight and cross-platform, high-level,
interpreted case-sensitive scripting language.
Q:- What is Scope? types of Scope in JavaScript?
Scope determines the availability or accessibility or visibility of variables, objects,
and functions.
Types of Scope:

There are mainly two type of scope in javascript

1. Global Scope
2. Local Scope
o Block Scope
o Function Scope

Q:- What is the difference between let and var?


The difference between let and var is of Scoping.

1. let gives you the privilege to declare variables that are limited in scope to the
block, statement of expression unlike var.
2. var is rather a keyword which defines a variable globally regardless of block
scope.

The both are very similar when used like the following, outside a function block.
 code
 source

1. let x = 'JavaScript interview questions'; // globally scoped


2.
3. var y = 'Advanced JavaScript'; // globally scoped
4.

Key Points:

Window Object: However, global variables defined with let will not be added as


properties on the global window object.
 code
 source

1. let x = 'JavaScript interview questions'; // globally scoped


2.
3. var y = 'Advanced JavaScript'; // globally scoped
4.
5.
6.
7. console.log(window.x); // undefined
8.
9. console.log(window.y); // 'Advanced JavaScript'
10.

Block Scope: let has block level scope.

Redeclaration: let and const variables cannot be re-declared while var variable can be


re-declared in the same scope.
 code
 source

1. 'use strict';
2.
3. let x = 'Hi, FullStackTutorials';
4.
5. let x = 'Hello, FullStackTutorials'; // SyntaxError: Identifier 'x' has
already been declared
6.

 code
 source

1. 'use strict';
2.
3. var y = 'Hi, FullStackTutorials';
4.
5. var y = 'Hello, FullStackTutorials'; // No problem, 'y' is replaced.
6.

Let's read more about - const in JavaScript ES6


Q:- What is difference between Function Declaration and Function Expression?
Function Declaration:
 code
 source

1. function myFunc(name) {
2.
3. return `Hello ${name}, Welcome to Advanced JavaScript Interview Questions`;
4.
5. }
6.
7. console.log(myFunc("User"));
8.
9.
10.
11. //Output
12.
13. Hello User, Welcome to Advanced JavaScript Interview Questions
14.

Function Expression:

A function expression can be stored in a variable and the variable can be used as a
function
 code
 source

1. var myFunc = function (name) {


2.
3. return `Hello ${name}, Welcome to Advanced JavaScript Interview Questions`;
4.
5. };
6.
7. console.log(myFunc("User"));
8.
9.
10.
11. //Output
12.
13. Hello User, Welcome to Advanced JavaScript Interview Questions
14.
There are many benefits of using function expressions

1. It can be used as Closure


2. It can be passed as arguments to other Function
3. It cab be used as Immediately Invoked Function Expressions (IIFE)

Function Expressions can not be Hoisted.


Q:- What is Immediately Invoked Function Expressions (IIFE) in JavaScript?

1. An IIFE (Immediately Invoked Function Expression) is a JavaScript function that


runs as soon as it is defined.
2. It is a design pattern which is also known as a Self-Executing Anonymous
Function

 code
 source

1. (function () {
2.
3. statements
4.
5. })();
6.

Example
 code
 source

1. var sum = (function (a,b) {


2.
3. return a+b;
4.
5. })(2,3);
6.
7. console.log(sum); // 5
8.
9.
10.
11. var sum = ((a,b) => {
12.
13. return a+b;
14.
15. })(2,3);
16.
17. console.log(sum); // 5
18.
19.
20.
21. (function (a,b) {
22.
23. console.log(a+b);
24.
25. })(2,3); //

Q:- What is Hoisting in JavaScript?

Hoisting is JavaScript's default behavior of moving all declarations to the top of


the current scope (to the top of the current script or the current function).

variables and function declarations are moved to the top of their scope before code
execution.

In JavaScript, a variable can be declared after it has been used. In other words, a
variable can be used before it has been declared.

code

source

x = 5; console.log(x); // Output: 5

var x;

JavaScript only hoists declarations, not initializations.

code

source

var x = 5;

2.

console.log('value is ' + x + ' and '+ y);

4.

var y = 10;

6.

7.

8.

//Output: value is 5 and undefined


10.

Note - Because variable y is not initialized before it is being used.

You may also like - Javascript ES6 Interview Questions

Q:- Is JavaScript a case sensitive language?

Yes, JavaScript is case sensitive.

Q:- What is functions JavaScript?

Anonymous Function - This type of function has no name.

code

source

var anonmFunc = function(){

2.

console.log("Advanced JavaScript Interview Questions and Answers");

4.

6.

Regular Named Function - This function is named properly and specifically.

code

source

function myFunc(){

2.

console.log("Advanced JavaScript Interview Questions and Answers");

4.

6.

Arrow Function - Arrow function (kind of anonymous function) is part of ES6.


Arrow functions is best suited with anything that requires this to be bound to the
context, and not the function itself.

Benefits of Arrow Functions

Shorter Syntax

No binding of this

code

source

//Regular Function

2.

function myFunc(){

4.

console.log("Advanced JavaScript Interview Questions and Answers");

6.

//Arrow Function

12.

var myFunc = () => {

14.

console.log("Advanced JavaScript Interview Questions and Answers");

16.

18.

Unlike a regular function, an arrow function does not bind this. Instead, this is
bound lexically (i.e. this keeps it's meaning from its original context).
An arrow function does not have its own this. this value of the enclosing lexical
scope is used by arrow functions. So if this is not present in current scope, an
arrow function ends up looking into lexical scope.

You may also like - React.js Interview Questions

Q:- What is Objects in JavaScript?

Object is an unordered collection of data in the form of key:value pairs.

A JavaScript object is an entity having State and Behavior (Properties


and Methods).

JavaScript is a prototype based language, so everything is an Object.

code

source

//A Simple Object Example

2.

3.

4.

var TV = {

6.

Name : "TV Name",

8.

Price: "15000",

10.

Color: "Black",

12.

SwitchON : function (){

14.

// Code Snippet
16.

},

18.

19. SwitchOFF : function (){

20.

21. // Code Snippet

22.

23. }

24.

26.

Q:- How many ways you can create an Object in JavaScript?

There are many ways to define or create an object in JavaScript.

Different ways of creating an Object in javascript:-

Object Literals

Object Constructor

Object.create Method

using Function

using Class

Object Literals:

code

source

let obj = {}

2.

code
source

let person = {

2.

name: "FullStackTutorials",

4.

getName: function() {

6.

return this.name;

8.

10.

11. };

12.

Object Constructor:

code

source

let person = new Object();

2.

person.name = "FullStackTutorials",

4.

person.getName = function(){

6.

return this.name ;

8.

};
10.

Object.create()

code

source

// Using Object.create() method:

2.

let person = Object.create(null);

4.

code

source

let data = {

2.

name: "FullStackTutorials",

4.

getName: function() {

6.

return this.name;

8.

10.

11. };

12.

let person = Object.create(data);

14.

Using Function:
code

source

function Person(name){

2.

this.name = name

4.

this.getName = function(){

6.

return this.name

8.

10.

11. }

12.

13.

14.

var obj = new Person("FullStackTutorials");

16.

console.log(obj);

18.

code

source

//Using Function Prototype

2.

3.
4.

function Person(name) {

6.

this.name = name;

8.

10.

Person.prototype.getName = function() {

12.

return this.name;

14.

};

16.

Using Class:

ES6 introduced the class keyword to create classes in JavaScript.

code

source

class Person {

2.

constructor(name, age) {

4.

this.name = name;

6.

this.age = age;

8.
}

10.

getInfo() {

12.

console.log(this.name + " Age : " + this.age);

14.

16.

18.

let perObj = new Person("Full Stack Tutorials", 25);

20.

Q:- What is the difference between Object.create and new Object?

Object.create() method creates a new object, using an existing object as the


prototype of the newly created object.

code

source

let Person = {

2.

age : 21,

4.

getIntro: function () {

6.

console.log(`Hey Guys, Myself ${this.name}. I am ${this.age} years old!`);

8.

}
10.

};

12.

let personObj1 = Object.create(Person);

14.

personObj1.name = "Full Stack Tutorials"; // "name" is a property set only on


"personObj", not on the "Person".

16.

personObj1.age = 25; // inherited properties can be overwritten

18.

personObj1.getIntro();

20.

21.

22.

23. let personObj2 = Object.create(Person);

24.

25. personObj2.getIntro();

26.

27.

28.

29. //Output

30.

31. Hey Guys, Myself Full Stack Tutorials. I am 25 years old!

32.

33. Hey Guys, Myself undefined. I am 21 years old!

34.
code

source

var person1 = new Object();

2.

person1.name = "Full Stack Tutorials",

4.

person1.getName = function(){

6.

return this.name ;

8.

};

10.

11.

12.

13. var person2 = new Object();

14.

person2.name = "Full Stack Tutorials",

16.

person2.age = 25,

18.

person2.getName = function(){

20.

return this.name ;

22.

23. };
24.

25.

26.

console.log(person1);

28.

console.log(person2);

30.

31.

32.

33. //Output

34.

35. {name: "Full Stack Tutorials", getName: ƒ}

36.

37. {name: "Full Stack Tutorials", age: 25, getName: ƒ}

38.

Q:- How can we compare two Array/Objects in JavaScript. Explain?

Primitives data types like strings and numbers are compared by their value, while
objects like arrays, dates, and plain objects are compared by their reference.

The comparison by reference basically checks to see if the objects given refer to the
same location in memory.

code

source

var a = {};

2.

var b = {};

4.
var c = a;

6.

7. console.log(a==b); //false

8.

9. console.log(a===b); //false

10.

11. console.log(a==c); //true

12.

13. console.log(a===c); //true

14.

Q:- What is a Closure in JavaScript?

A closure is a feature in JavaScript where an inner function has access to the outer
(enclosing) function's variables.

It has access to it's own scope i.e. variables defined between its curly
brackets.

It has access to the outer function's variables.

It has access to the global variables.

code

source

function outer() {

2.

var a = 10;

4.

function inner() {

6.

var b = 20;
8.

console.log(a+b);

10.

12.

13. return inner;

14.

16.

Q:- Write the output of the following javascript programs?

code

source

for (var i = 0; i < 5; i++) {

2.

setTimeout(() => {

4.

5. console.log(i);

6.

}, 1000);

8.

10.

11.

12.

13. //Output
14.

(5) 5

16.

Reason: It will reference the last value stored in i, which was 5.

There are two solution to resolve this problem

Closure

let

Closure It creates a unique scope for each iteration, storing each unique value of
the variable within it's scope.

code

source

for (var i = 0; i < 5; i++) {

2.

(function(x) {

4.

5. setTimeout(() => {

6.

console.log(x);

8.

}, 1000);

10.

})(i);

12.

14.

15. //Output
16.

18.

20.

22.

24.

25. 4

26.

code

source

for (let i = 0; i < 5; i++) {

2.

setTimeout(() => {

4.

5. console.log(i);

6.

}, 1000);

8.

10.

11.

12.
//Output

14.

16.

18.

20.

21. 3

22.

24.

Reason: let has block level scope so variable i is only seen in the for loop's block
scope.

Q:- What is Callback Functions?

A callback function is a function passed into another function as an argument(let’s


call this other function "otherFunction"), and the callback function gets executed
inside the otherFunction after the function has finished execution.

code

source

function doHomeWork(subject, callback) {

2.

alert(`Starting my ${subject} homework.`);

4.

5. callback();

6.
}

8.

function alertFinished(){

10.

alert('Finished my homework');

12.

14.

doHomeWork('Computer Science', alertFinished);

16.

Q:- Why do we need Callbacks?

JavaScript is an event driven language. This means that instead of waiting for a
response before moving on, JavaScript will keep executing while listening for other
events.

Callbacks are a way to make sure certain code doesn't execute until other code has
already finished execution.

You may also like - Node.js Interview Questions and Answers

Q:- What is Prototype?

In JavaScript, objects have a special hidden property [[Prototype]] (as named in the
specification), that is either null or references another object. That object is
called "Prototype".

Q:- What is Prototypal Inheritance?

That [[Prototype]] has a "magical" meaning. When we want to read a property from
object, and it’s missing, JavaScript automatically takes it from the prototype. In
programming, such thing is called "prototypal inheritance"

The property [[Prototype]] is internal and hidden, but there are many ways to set it.
via __proto__or Object.getPrototypeOf // old-way

obj.__proto__
// new-way

Object.getPrototypeOf(obj)

The __proto__ is considered outdated and somewhat deprecated (in browser-only part of
the Javascript standard).

The modern methods are:

Object.create(proto[, descriptors]) – creates an empty object with given


proto as [[Prototype]] and optional property descriptors.

Object.getPrototypeOf(obj) – returns the [[Prototype]] of obj.

Object.setPrototypeOf(obj, proto) – sets the [[Prototype]] of obj to


proto.

code

source

var a = { name: "Full Stack Tutorials" };

2.

a.__proto__ === Object.prototype // true

4.

5. Object.getPrototypeOf(a) === Object.prototype // true

6.

7.

8.

function Foo() {};

10.

var b = new Foo();

12.

b.__proto__ === Foo.prototype


14.

b.__proto__.__proto__ === Object.prototype

16.

Q:- What is the difference between classical and prototypal inheritance?

Classical Inheritance: A constructor function instantiates an instance via the new


keyword. This new instance inherits properties from a parent class.

Prototypal Inheritance: An instance is created by cloning an existing object that


serves as a prototype. This instance—often instantiated using a factory function or
"Object.create()"—can benefit from selective inheritance from many different objects.

Q:- What is Promise in JavaScript?

A promise is an object which can be returned synchronously from an asynchronous


function.

Promise overcome the problem of callback hell.

Promise States:

Fulfilled: onFulfilled() will be called (e.g. resolve() was called).

Rejected: onRejected() will be called (e.g. reject() was called).

Pending: initial state, neither fulfilled nor rejected.

Promise Consumers: then, catch, finally

code

source

var promise = new Promise(function(resolve, reject) {

2.

const A = "fullstacktutorials";

4.

5. const B = "fullstacktutorials"

6.
if(A === B) {

8.

resolve();

10.

} else {

12.

reject();

14.

16.

});

18.

19.

20.

21. promise.

22.

then(function () {

24.

console.log('Success, Your promise has been resolved successfully');

26.

}).

28.

catch(function () {

30.

console.log('Something went wrong!');


32.

33. });

34.

Example:- Write a function compareToTen that takes a number as an argument and


returns a Promise that tests if the value is less than or greater than the value 10.

code

source

const compareToTen = (num) => {

2.

p = new Promise((resolve, reject) => {

4.

5. if(num > 10) {

6.

7. resolve(num + " is greater than 10, success!")

8.

} else {

10.

reject(num + " is less than 10, error!")

12.

14.

})

16.

return p

18.

}
20.

21.

22.

23. compareToTen(15)

24.

25. .then(result => console.log(result))

26.

.catch(error => console.log(error))

28.

29.

30.

compareToTen(8)

32.

.then(result => console.log(result))

34.

35. .catch(error => console.log(error))

36.

Q:- What is the difference between call and apply?

apply():

The apply() method calls a function with a given this value, and arguments provided
as an array.

Syntax: fun.apply(thisArg, [argsArray])

call():

The call() method calls a function with a given this value and arguments provided
individually

Syntax: fun.call(thisArg[, arg1[, arg2[, ...]]])


code

source

function myFunction(name, profession) {

2.

console.log("My name is " + name + " and I am a " + profession +".");

4.

5. }

6.

7. myFunction("John", "Developer");

8.

myFunction.apply(this, ["Ajay", "Designer"]);

10.

myFunction.call(this, "Ravi", "Blogger");

12.

13.

14.

//Output:

16.

My name is John and I am a Developer.

18.

My name is Ajay and I am a Designer.

20.

My name is Ravi and I am a Blogger.

22.

23.
24.

A useful mnemonic is "A for array and C for comma."

bind():

bind allows you to set the this value now while allowing you to execute the function
in the future, because it returns a new function object.

Syntax: fun.bind(thisArg[, arg1[, arg2[, ...]]])

Q:- What is the spread operator in JavaScript?

The spread operator (…) is a new operator introduced in ES6. It allows the expansion
of an iterable (e.g., Array) into its constituent elements.

code

source

var childArr = [1, 2, 3];

2.

var finalArr = [...childArr, 4, 5, 6];

4.

5.

6.

7. console.log(finalArr);

8.

//Output: [1, 2, 3, 4, 5, 6];

10.

Q:- Remove the duplicate elements from the Array?

Using ES6 - Spread & Set Operator

Using jQuery each function

Using ES6 - Spread & Set Operator:

code
source

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

2.

3.

4.

5. function removeDuplicates(array) {

6.

7. return [...new Set(array)];

8.

10.

11.

12.

13. console.log(removeDuplicates(numbers)); // [1, 2, 3, 4, 5]

14.

Set was introduced in ES6: They can't have duplicate Items.

After we have done that, we simply convert the Set back to an array by using the
spread operator.

Using jQuery each function:

code

source

var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];

2.

var uniqueNames = [];

4.

5. $.each(names, function(i, el){


6.

7. if($.inArray(el, uniqueNames) === -1) {

8.

uniqueNames.push(el);

10.

12.

13. });

14.

console.log(uniqueNames); // ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Carl"]

16.

Q:- What are the advantages of using JavaScript?

Following are the advantages of using JavaScript:

Lightweight: JavaScript can be executed within the user’s browser without having to
communicate with the server, saving on bandwidth.

Speed: Client-side JavaScript is very fast because it can be run immediately within
the client-side browser.

Simplicity: JavaScript is relatively simple to learn and implement.

Versatile: JavaScript supports multiple programming paradigms—object-oriented,


imperative, and functional programming and can be used on both front-end and server-
side technologies.

Interactivity: Because tasks can be completed within the browser without


communicating with the server, JavaScript can create a smooth "desktop-like"
experience for the end user.

Rich Interfaces: From drag-and-drop blocks to stylized sliders, there are numerous
ways that JavaScript can be used to enhance a website’s UI/UX.

Prototypal Inheritance: Objects can inherit from other objects, which makes
JavaScript so simple, powerful, and great for dynamic applications.
Platform Independent: JavaScript is platform independed language. Any JavaScript-
enabled browser can understand and interpreted JavaScript code.

Q:- What is JavaScript Design Patterns?

Design patterns are advanced object-oriented solutions to commonly occurring software


problems.

Creational Design Patterns:

As the name suggests, these patterns are for handling object creational mechanisms.

Constructor pattern

Factory pattern

Prototype pattern

Singleton pattern

Structural Design Patterns:

This pattern helps to obtain new functionalities without tampering with the existing
ones.

Adapter

Bridge

Composite

Decorator

Facade

Flyweight

Proxy

Behavioral Design Patterns:

These patterns are concerned with improving communication between dissimilar objects

Iterator pattern

Observer pattern

Template pattern
Strategy pattern

State pattern

Command pattern

Q:- Does JavaScript support Method Overloading?

No, JavaScript does not support overloading!. JavaScript supports overriding not
overloading.

code

source

function getSum(n1, n2, n3) {

2.

return n1 + n2 + n3;

4.

6.

function getSum(n1, n2) {

8.

return n1 + n2;

10.

12.

var sum = getSum(2, 3, 10);

14.

15. console.log(sum); // 5

16.
If you will define two or more functions with the same name, the last one will
override the previously defined functions and when a call will be made to the
function, the last defined function will get executed.

Q:- Why typeof null return object in JavaScript?

Yes, it's true. since null is a primitive datatype still typeof null return object.

code

source

typeof null // "object" (not "null" for some legacy reasons)

2.

You might also like