Introduction
JavaScript is a versatile and widely-used programming language. If you're a JavaScript developer looking for your next job, you will likely face some tough interview questions. Employers want to make sure they're hiring the best candidates for the job.
To help you prepare for your next JavaScript interview, we've compiled a list of expert tips and tricks for acing your interview. From understanding the basics of JavaScript syntax and concepts to knowing how to answer common interview questions, this guide has everything you need to succeed.
So whether you're a seasoned JavaScript developer or starting, read on for our top questions and answers.
Question 1. What is JavaScript?
Answer
Wiki says, “JavaScript is a high-level, dynamic, untyped, and interpreted programming language. It has been standardized in the ECMAScript language specification. Alongside HTML and CSS, it is one of the three core technologies of World Wide Web content production; most websites employ it, and all modern Web browsers support it without plug-ins.
JavaScript is prototype-based with first-class functions, making it a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles. It has an API for text, arrays, dates, and regular expressions. Still, it does not include any I/O, such as networking, storage, or graphics facilities, relying for these upon the host environment in which it is embedded”.
Fundamentals Of JavaScript
- There are no specific data types (e.g-var t) in JavaScript.
- There are if for, switch, while, do-while, break, and continue, similar to Java or C# in JavaScript.
- document.write() is used to display an output in JavaScript.
- There are some dialogues in JavaScript, which are as follows- Alert- OK
Confirm- OK/CANCEL
Prompt- Input
- Function- A 'function' keyword is used for function in JavaScript.
Some Examples of JavaScript
A simple program of JavaScript.
<html>
<head>
<title>MY TITLE</title>
</head>
<body>
<script type="text/javascript">
document.write("Most Welcome in JavaScript")
</script>
</body>
</html>
Output

For more details, visit the following link,
Question 2. Explain Frames in JavaScript
Answer
Frames allow you to divide the page into several rectangular areas and to display a separate document in each rectangle. Each of those rectangles is called a "frame".
Here is an example
<FRAMESET ROWS="75%, *" COLS="*, 40%">
<FRAME SRC="framea.html">
<FRAME SRC="frameb.html">
<FRAME SRC="framec.html">
<FRAME SRC="framed.html">
<NOFRAMES>
<H1>No Frames? No Problem!</H1>
Take a look
<A HREF="noframes.html">no-frames</A>
The version is
- </NOFRAMES>
- </FRAMESET>
Nested Frames
<FRAMESET ROWS="15%,*">
<FRAME SRC="titlebar.html" NAME=TITLE SCROLLING=NO>
<FRAMESET COLS="20%,*">
<FRAME SRC="sidebar.html" NAME=SIDEBAR>
<FRAME SRC="menu.html" NAME=RECIPES>
</FRAMESET>
<NOFRAMES> No frames? No Problem! Take a look at our
<A HREF="menu.html">no-frames</A> version. </NOFRAMES>
</FRAMESET>
Targeting Frames
Each frame is given a name using <FRAME NAME="...">. These names uniquely identify each frame. Using these names, the links in other frames can tell the Browser which frames the link target.
<FRAMESET COLS="20%,*">
<FRAME SRC="sidebar.html" NAME=SIDEBAR>
<FRAME SRC="main.html" NAME=MAIN>
</FRAMESET>
To target one of these frames, the link should have a TARGET attribute set to the frame's name, where the linked page should appear. Thus, for example, this code creates a link totfetacos.html and targets the link to the MAIN frame,
<A HREF="tfetacos.html" TARGET=MAIN>my link</A>
For more details, visit the following link,
Question 3. What are the JavaScript Operators?
Answer
JavaScript addition operator ( + ) serves two primary purposes in JavaScript. The first is to perform a simple addition on the numbers.
The second operation is to perform a string concatenation (combine the strings).
Addition
<script>
var a = 3;
var b = 2;
var c = a + b;
document.write(c);
</script>
JavaScript subtraction operator
JavaScript subtraction operator ( - ) also serves two purposes in your code. The first is simply subtracting the numbers (6 - 2). The second operation is to specify negative numeric values (-20).
Subtraction
<script>
var a = 10;
var b = 3;
var c = a - b;
document.write(c);
</script>
JavaScript multiplication operator
JavaScript multiplication operator ( * ) is used to multiply the numbers.
<script>
var a = 4;
var b = 3;
var c = a * b;
document.write(c);
</script>
JavaScript division operator
JavaScript division operator ( / ) is used to divide the numbers.
<script>
var a = 8;
var b = 4;
var c = a / b;
document.write(c);
</script>
JavaScript increment operator
JavaScript increment operator ( ++ ) is used to increase a number by 1.
Example
<script>
var i = 0;
i++;
document.write(i);
</script>
JavaScript decrement operator
JavaScript decrement operator ( -- ) decreases a number by 1.
Example
<script>
var i = 1;
i--;
document.write(i);
</script>
For more details, visit the following link,
Question 4. Explain JavaScript Statements
Answer
JavaScript block statement
JavaScript block statements are the curly braces ( { } ) you see everywhere. They are used to categorize the code into a specific function or statement.
The code lines inside a block statement are often intended to represent that they are part of the block statement. The following examples show the curly braces establishing the blocks of the compartmentalized code.
<script>
if (3 < 5) {
// code for this block statement goes in here
}
for (var i = 0; i < 10; i++) {
// code for this block statement goes in here
}
function myFunction() {
// code for this block statement goes in here
}
</script>
JavaScript break statement
The JavaScript break statement terminates a loop, switches, or labels the statement from further processing. Apply it when you want to force one of those types of statements to stop the processing.
Example of terminating a loop using break
<script>
for (i = 0; i < 20; i++) {
if (i >= 5) {
break;
}
document.write("Pass index " + i + " of the loop<br />");
}
</script>

JavaScript continue statement
JavaScript's continue statement is used to bypass the specified iterations of a loop so that the code in the loop statement does not execute for the specified iterations and moves on to the next.
<script>
for (i = 0; i < 20; i++) {
if (i < 10) {
continue;
}
document.write("Pass index " + i + " of the loop<br />");
}
</script>

JavaScript do-while statement
JavaScript do-while statement is an inverted while statement. It will execute the code as long as the while condition returns a true value.
<script>
var i = 0;
do {
document.write("Loop index: " + i + "<br />");
i++;
}
while (i < 5);
</script>

JavaScript for statement
JavaScript for statement is a loop mechanism, which will execute code as long as the condition evaluation continues to be true.
<script>
for (var i = 0; i < 5; i++) {
document.write("Pass index " + i + " of the loop<br />");
}
</script>

For more details, visit the following link,
Question 5. Explain JavaScript objects
Answer
Objects are the data types of JavaScript. Each variable that you create or literal value that you work with is an object with specific methods and properties that you can access when working with that type of data, which is one of the biggest aspects of understanding any modern scripting language.
JavaScript supports automatic data type casting for the objects. It simply means that we do not have to explicitly define each variable's data type as we create them unless our script demands it. JavaScript also allows a script author to create custom objects to extend the language.
JavaScript Standard Objects
- String Object - For working with the string data in JavaScript.
- Array Object - For compartmentalized data processing.
- Date Object - For date and time programming.
- Math Object - For mathematical calculations in JavaScript.
- Number Object - For working with the numeric data in JavaScript.
- RegExp Object - For matching a text against a pattern.
- Boolean Object - For representing false and true values.
- Function Object - For calling the dormant segments of your code to run.
- object Object- Extend JavaScript by creating your custom objects
For more details, visit the following link,
Question 6. Explain Arrays in JavaScript
Answer
An array is a collection of similar data types. All its values are stored in the index locations, starting from 0 to n-1.
Declaration of an Array
var myArray = [];
var myArray = [value1, value2, value3, so on...];
var myArray = new myArray(length_of_array);
Let's understand this with the following examples
Example
var myArray = [20, 30, 40, 50];
for (var i = 0; i <= myArray.length - 1; i++) {
document.write("The value at the index location " + i + " is " + myArray[i] + " <br/>");
}
The preceding code declares an array with 4 values. The for loop is used, which starts the index value "i" from 0 until the length of "myArray", and the index location is incremented by 1.
The written property of the document object displays the values at the index location, which is implemented using myArray[i] and HTML Break so that each index location's value is displayed in a different line.
Example
var myevenNumbersArray = [];
for (var i = 0; i <= 5; i++) {
myevenNumbersArray[i] = i * 2;
}
for (var i = 0; i < myevenNumbersArray.length; i++) {
document.write(myevenNumbersArray[i] + "<br/>");
}
The preceding code prints all the even numbers stored in the array. This time, we are adding the values to the array dynamically. We have used a for loop to do this. First, we have declared an array whose size is not defined. Thus, it can contain as many values as we want. We have used a for loop starting from 0 and going to 5. The value of the index location is multiplied by 2 each time; the interpreter iterates through the loop. Thus, 5 values will be stored in the array. In other words, 0, 2, 4, 6, 8, and 10.
For more details, visit the following link,
Question 7. What is a screen object in JavaScript?
Answer
The screen object helps in getting the information on the user's screen. We can get the user's screen's width, height, color depth, etc.. This information will help set the size of the images and page to be displayed in the Browser. We will look into the properties of the screen object by an example.
Create a sample ASP.NET Web Application and a button, label, and add JavaScript code, given below,
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function showScreenData() {
document.getElementById("lblScreenDetails").innerText = "Total Height: " + screen.height + " Total Width: " + screen.width + " Available Height: " + screen.availHeight + " Available Width: " + screen.availWidth + " Available Pixel Depth : " + screen.pixelDepth + " Available Color Depth : " + screen.colorDepth + " Buffer Depth : " + screen.bufferDepth;
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div> </div>
<asp:Button ID="btnScreenData" runat="server" Text="Get Screen Details" OnClientClick="return showScreenData()" /> <br />
<asp:Label ID="lblScreenDetails" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
Now, run the Application. It will show the properties of the screen, like width, pixel depth, etc., as shown below,

This way, we can access the user's screen properties to adjust the images/page size accordingly.
Using the screen object, we can access the properties below on the user's screen.
| Property Name | Description |
| availHeight | Available Height |
| availWidth | Available Width |
| bufferDepth | - |
| colorDepth | - |
| deviceXDPI | - |
| deviceYDPI | - |
| height | Screen height |
| width | Screen width |
| logicalXDPI | - |
| logicalYDPI | - |
| fontSmoothingEnabled | - |
| updateInterval | - |
For more details, visit the following link,
Question 8. What are Math Objects in JavaScript?
Answer
The Math object is used to perform simple and complex arithmetic operations.
The main properties and methods of Math Objects are given below:
Properties of Math Object in JavaScript
- E- Holds the Euler's Number
- LN2 - Natural Logarithm of 2.
- LN10 - Natural Logarithm of 10.
- LOG2E - Base 2 Logarithm of E.
- LOG10E - Base 10 Logarithm of E.
- PI - Numerical Value of PI(22/7 or 3.142)
- SQURT1_2 - Square root of 2.
- SQRT2- Square root of 2.
These are some main properties of Math objects in JavaScript. Now, let's learn about the methods in JavaScript. There is a long list of the methods for the Math objects, and some of them are given below,
Methods of Math Object in JavaScript
- abs (x) - Return the absolute value of x.
- acos (x) - Return the arccosine (in radian) of x.
- asin (x) - Return arcsine (in Radian) of x.
- atan (x) - Returns the arctangent of x with numeric value b/w -PI/2 to +PI/2.
- atan2 (y,x) - Returns the arctangent of quotient on dividing y and x.
- ceil (x) - Rounds up x to the nearest bigger integer.
- cos (x) - Return cosine value of x.
- exp (x) - Returns the value of ex.
- floor (x) - Rounds up x to the nearest smaller integer.
- log (x) - Returns the natural logarithmic value of x.
- max (x,y,z,....n) - Returns the highest number from the given list.
- min (x,y,z,.......) - Returns the smallest number from the given list.
- pow (x,y)- Returns the x to the power of y.
- random ()- Returns a Random number.
- round (x)- Rounds up x to the nearest integer.
- sin (x) - Return the sine value of x.
- sqrt(x) - Returns the square root of x.
- tan (x) - Returns the tangent value of x.
For more details, visit the following link,
Question 9. What are the common Errors in JavaScript?
Answer
The common errors in JavaScript programming are the following,
- Spelling and typing errors.
- Missing brackets or quotation marks.
- Mismatching quotation marks.
- Using a single equal sign instead of the double equal sign in comparison.
- Referencing objects that do not exist.
- Using reserved keywords for the variable naming.
- Using the wrong type of brackets.
These are the main causes of these errors. In JavaScript, there are the following three types of errors,
- Syntax Error in JavaScript
- Runtime Error in JavaScript
- Logic Error in JavaScript
Let's understand them one by one.
Syntax Error in JavaScript
Syntax errors are those errors that occur when we violate the rules defined by JavaScript. These errors occur when a Web Page that has been created is loaded.
Example
We are writing a script to display the value of a variable, but somewhere in the program, you forgot the closing parentheses and a syntax error would occur. The Syntax errors prevent JavaScript code from functioning. A Browser shows the error message with the specified line when it encounters a JavaScript code error.
Runtime Errors in JavaScript
Runtime errors inform the user that there is a problem with a script. Similar to syntax errors, runtime errors are also displayed in a Browser. The nature of the error, along with a line number, as specified in an alert box, so you can easily search for the script. Runtime errors mainly occur due to improper use of the commands.
For instance, you will review runtime errors if you reference a variable that has not been defined. The following code snippet shows an example of a runtime error.
Sting = "C# Corner";
document.write (sing);
In the given code, we have declared a string variable, string, and assigned the value "C# Corner" to it. Next, we displayed its value, but instead of "Sting", we wrote "sing", which is not declared. Therefore, the second line of the preceding code snippet generates a runtime error.
Logic Errors in JavaScript
Another common error type is logic, which occurs when your script code does something different than the one suggested by the logic. Errors occur when the code is miswritten, and you do not get the expected results. These errors are commonly known as bugs. Let's consider the following code,
Example
<SCRIPT>
var status = 25;
var port
LogicErrors - Notepad
80, host = "xyz.com";
function connect(status, host) {
this do something = function(host, port) {
if (post=60) {
alert("Good: 80 is standard port for http");
}
else {
alert("bad: Non standard port");
alert("The host is "+this.host);
}
}
}
var connection = new Connect(status, host);
connection.do_something(host);
<SCRIPT>
For more details, visit the following link,
Question 10. Explain Page Re-direction in JavaScript
Answer
Page redirection means moving to another location or page using JavaScript on the client side. Sometimes, you visit a specific Website, but it goes to another page because it is internally redirected. If you see the shopping Website: Amazon, it will show the image like,

It will show you a pop-up message “Shopping from India? Looking for Amazon.in?” with two options, the first “Stay on Amazon.com” and the second “Go to Amazon.in”, and when you click on the second option, the page will be redirected to Amazon.
There are multiple reasons to redirect from the original page, as follows,
- One reason is that we just discussed this in the previous example. The Browser gets your location and asks for the page change, and the button clicks event page is redirected.
- If you have created a new domain and want to redirect all your visitors from the old to the new domain.
The following are the various page redirection methods to redirect from one page to another in JavaScript.
These methods are used for redirecting to another page; add this code to the head section,
Using window.location
<script type="text/javascript">
<!--
window.location = "https://www.c-sharpcorner.com";
//-->
</script>
Using window.location.href.
<script type="text/javascript">
<!--
window.location.href = "https://www.c-sharpcorner.com";
//-->
</script>
Using window.location.assign.
<script type="text/javascript">
<!--
window.location.assign = "https://www.c-sharpcorner.com";
//-->
</script>
Using window.location.replace.
<script type="text/javascript">
<!--
window.location.replace = "https://www.c-sharpcorner.com";
//-->
</script>
Using window.open.
<html>
<head>
<script type="text/javascript">
<!--
function WinOpen() {
window.open("https://www.c-sharpcorner.com/", "OpenWindow", "status = 1, height = 450, width = 450, resizable = 0")
}
//-->
</script>
</head>
<body> <input type="button" onClick="WinOpen()" value="WinOpen"> </body>
</html>
For more details, visit the following link,
Question 11. Explain the Scope and Events in JavaScript
Answer
Scope in JavaScript
The scope defines the accessibility of a variable, objects, and function. It is nothing but the boundary line. There are only two types of scope present in JavaScript, as follows,
- Local Scope in JavaScript
- Global Scope in Script
Local Scope in JavaScript
It defines that something is only accessible on a limited scope. When you declare a variable within the function, it becomes local to that function. It's not accessible to the other functions or outside the function.
<!DOCTYPE html>
<html>
<title>Scope in JavaScript</title>
<head></head>
<body>
<script language='javascript'>
AuthorName();
document.write("</br>Outside the function</br>");
//can not access the author variable to outside
document.write("</br>Author is " + typeof author);
document.write();
function AuthorName() {
//local variable declaration means local scope
var author = "Jeetendra";
document.write("</br>Inside the function </br>Author is " + author + "</br>");
}
</script>
</body>
</html>
Output
Inside the function
Author is Jeetendra
Outside the function
Global Scope in JavaScript
It can be accessible to other functions as it becomes global to all. You can access it within the function. It is defined anywhere in your JavaScript code.
<!DOCTYPE html>
<html>
<title>Scope in JavaScript</title>
<head></head>
<body>
<script language='javascript'>
document.write("Global Scope in JavaScript</br>");
//global variabe declaration
var name = "krishna"; //it can be accessible to all within JavaScript code
Name();
function Name() {
//access the test variable,
//it can be accessible because it is global in scope
document.write("My Name is " + name);
}
</script>
</body>
</html>
Output
Global Scope in JavaScript
My Name is Krishna
Events in JavaScript
The following figure shows the object hierarchy in JavaScript. All objects have properties and methods. Some objects also have "events". Every element on a Web page has certain events that can trigger the invocation of the event handlers. The "event handler" is a commandused to specify the actions in response to an event. Attributes are inserted into HTML tags to define the events and event handlers.
Examples- The following are examples of events,
- A mouse click.
- A web page or an image loading.
- Moussing over a hot spot on the web page.
- Selecting an input box in an HTML form.
- Submitting an HTML form.
- A keystroke.
Example- OnClick event example.
<!DOCTYPE html>
<html>
<head>Event Example</head>
<body> <button onclick="clickme()">Click me</button>
<script language='javascript'>
function clickme() {
alert("OnClick Event of Button");
}
</script>
</body>
</html>
Run the preceding code, and it will show you a button. When you click the button, it will pop up a message box, as shown in the following output,
Output

For more details, visit the following link,
Question 12. What are the types of comments in JavaScript?
Answer
In JavaScript, the comments are used for skipping that statement from execution. Using the comments smakes the code more readable and understandable for anyone. Code functionality is clearer using the comments. The following comments are used in JavaScript,
- Single Line Comment
- Multi-line comment
Single Line Comment
A single-line comment is used when you want to comment on a single statement. It starts with "//". Using this, you can comment out an entire line. JavaScript ignores this line.
The following example uses a single-line comment to explain the code,
<!DOCTYPE html>
<html>
<title>JavaScript Comments</title>
<head></head>
<body>
<script language="javascript">
//Single line comment
//Addition of two numbers
var a = 25;
var b = 75;
var c = a + b; //addition of a and b is store in c variable
document.write("Addition of " + a + " and " + b + " is " + c);
</script>
</body>
</html>
Output
Addition of 25 and 75 is 100
Multi-line Comment
A multi-line comment is used with a group or the code block you want to comment on. A multi-line comment starts with /* and ends with */. JavaScript skips the code block between this.
In the following example, a group of statements is commented out using multi-line comments.
<!DOCTYPE html>
<html>
<title>JavaScript Comments</title>
<head></head>
<body>
<script language="javascript">
/*
var a = 25;
var b = 75;
var c = a + b; //addition of a and b is store in c variable
document.write("Addition of " + a + " and " + b + " is " + c);
*/
function Print() {
document.write("Example of Multi-line Comments in JavaScript");
}
Print();
</script>
</body>
</html>
Output
Example of the Multi-line Comments in JavaScript
For more details, visit the following link,
Question 13. Explain Exception Handling in JavaScript
Answer
This is a new feature of JavaScript for handling the exceptions like in other programming languages, using try-catch finally statements and the throw operator for handling the exceptions. Now, you can catch the runtime exception.
The try block is always used before a catch block because, in a try block, you provide your code to be executed. If there is no error in the code, the catch block is not executed, but the final block is always executed. The following example shows an exception handling.
Example
<!DOCTYPE html>
<html>
<title>Article By Jeetendra</title>
<head> </head>
<body>
<script type="text/javascript">
document.write("Exception Handling in JavaScript</br>");
function ExceptHand() {
try {
alert("This is try block");
alert("Not present");
} catch (error) {
document.write(error);
}
}
ExceptHand();
</script>
</body>
</html>
When you execute this program, it will first show an alert message box with “This is a try block”. When it executes the next statement, it is an error because no alert message box is available for this exception. It will print the proper exception message like the following output,
Output

For more details, visit the following link,
Question 14. Explain the performance of JavaScript code
Answer
There are ways to speed up your JavaScript code performance.
- Reduction of activities in loops- In our programming, we often use loops for iteration. Every statement inside a loop is executed for each iteration of the loop. The statements or assignments to be searched can be placed outside the loop.
- Reduction of DOM Access- Compared to other JavaScript statements, accessing the HTML DOM is very slow. If you want to access the DOM element several times, access it once and use it as a local variable. This is how you can access your DOM element easily as many times as you want.
Output<html> <body> <p id="dom"></p> <script> var obj; obj = document.getElementById("dom"); obj.innerHTML = "Hello JavaScript..!!"; </script> </body> </html>
- Avoid Unnecessary variables- Avoid creating new variables that are not useful to save any value. This will unnecessarily create a loading problem. You can replace your code by optimizing the code.
<p id="dom"></p> <script> var fullName = firstName + "" + lastName; fullName = document.getElementById("dom"); fullName.innerHTML = fullName; </script>
After reduction or optimization
<p id="dom"></p> <script> document.getElementById("dom").innerHTML = firstName + "" + lastName; </script>
For more details, visit the following link,
Question 15. Is JavaScript case-sensitive?
Answer
Yes, JavaScript is a case-sensitive scripting language. Variable names, keywords, methods, and event handlers are all case-sensitive.
Example
In the previous part of this series, we saw how to use an alert function. We will be using the same alert function for this example.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
alert('alert function invoked');
</script>
</body>
</html>
We have a very pretty simple example. All we have is a script tag in the body section.
Inside the script tag, all we are doing is, we are calling the alert function. Thus, when we open this file in a Browser, the Browser will execute this JavaScript.

For more details, visit the following link,
Question 16. Describe JavaScript Anonymous Functions
Answer
A function without a name is an anonymous function. We store these inside a variable name. Thus, the invocation happens using the variable name.
Below is an example
var sum = function(a,b){return a+b;};
sum();
Advantages of an anonymous function
The first advantage is that JavaScript allows you to pass an anonymous function as an object to the other functions. You don’t need to explicitly define the function before passing it as a parameter to the other function. The example below is a distance calculator between the two points. In the method calculateDistanceMetres, we’re passing an anonymous function.
function calculateDistanceMetres(pointA, pointB, method) {
var value = method();
return (pointB - pointA) * value;
}
console.log(calculateDistanceMetres(10, 20, function() {
return 1000;
}));
What if we don’t pass an anonymous function?
console.log (calculateDistanceMetres(10,20));
It will throw an error because method() cannot execute any code.

To solve the above case, let us adjust our code, which will cover both scenarios,
function calculateDistanceMetres(pointA, pointB, method) {
if (method) {
var value = method();
return (pointB - pointA) * value;
} else {
return (pointB - pointA);
}
}
console.log(calculateDistanceMetres(10, 20)); //output 10
console.log(calculateDistanceMetres(10, 20, function() {
return 1000;
})); //output 10000
Disadvantages of an anonymous function
- If you have an extensive program, debugging is tough because you don’t know the function's name in the call stack. The call stack will show it as an anonymous function. Debug the above program in Chrome & see Call Stack. You can notice an anonymous function when the execution is at code function () { return 1000; }

- These functions cannot be reused.
- These functions cannot be unit tested easily. Therefore, you may need to refactor the code.
For more details, visit the following link,
Question 17. Explain different types of JavaScript functions invocations.
Answer
Functions are first-class citizens in JavaScript. There are many ways to declare the functions in JavaScript. Let's understand each.
Function Declaration
The traditional way of defining a function is,
function logMe() //function name logMe
{
console.log('Log me in');
}
logMe();
Function hoisting
It is the process in which JavaScript runtime hoists all the functions declared, using the function declaration syntax at the top of the JavaScript file. Look at the example given below,
function logMe() {
console.log('Log me in');
}
logMe();
function logMe() {
console.log('Log me again');
}
logMe();
Function expression
It’s the second form of declaring a function.
var log = function() {
console.log('Log me in');
}
Anonymous function
It’s a function without a name. You can assign a function to a variable. Another way of declaring an anonymous function is within an object literal. For example,
var programmer = {
lang: 'Javascript',
browser: 'Chrome',
getFullSpecs: function() {
console.log(this.lang + ' running inside ' + this.browser);
}
}
Function() Constructor
The function() constructor expects any number of string arguments. The last argument is the function's body; it can contain arbitrary JavaScript statements separated from each other by semicolons.
var multiply = new Function("x","y","var z=x*y; return z;");
multiple(10,20);
Output
200
For more details, visit the following link,
Question 18. What is Closure in JavaScript?
Answer
A closure is a local variable that will be executed after the specific function has returned. A Closure provides a free environment where the outer function can easily access the inner functions and inner variables without any scope restrictions.
Example
<html>
<head>
<script type="text/javascript" language="JavaScript">
function ExClosure(a, ref1) {
var v1 = a;
var ref = ref1;
return function(v2) {
v1 += v2;
alert("Add:" + v1)
alert("Reference Value:" + ref.cv);
}
}
myclosure = ExClosure(10, {
cv: 'My First Closure'
});
myclosure(5);
</script>
</head>
<body onload="ExClosure(b,ref)"> </body>
</html>
In this example, when the ExClosure function is called, it returns a function. The function remembers the value of a (10) in the form of v1, which means the myclosure will add 10 together with 5 and return 15 as an alert, and the next alert returns the Reference value (Reference Value: My First Closure).
Output


For more details, visit the following link,
Question 19. Explain the Generic Function in JavaScript.
Answer
A generic function in JavaScript is similar to "String.IsNullOrEmpty" of C# to check whether the specified string is null or empty.
How often do we check a string for Null, Undefined & empty string in a JavaScript code? Here is my fundamental method StringHasValue to check if a string is either null, #ff0000 or an empty string (The string to be checked may contain the white spaces is also considered). Although it’s a fundamental method, it will save time, require less coding effort & will be less error-prone.
var StringHasValue = function(strValue) {
if ($.trim(strValue) != "" && $.trim(strValue) != null && $.trim(strValue) != undefined) return true;
else return false;
};
For more details, visit the following link,
Question 20. Explain Break Statement in JavaScript
Answer
A break statement allows you to break or exit a loop. When used inside a loop, the break statement stops executing the loop and causes the loop to be immediately exited. The statements do not execute if the loop has statements after the break statement, the statements do not execute.
Write the following code,
<!DOCTYPE HTML>
<HTML>
<HEAD>
</HEAD>
<BODY>
<TITLE>Using the break statement
</TITLE>
<H1>Using the break statement.
</H1>
<SCRIPT type="text/javascript"> var count=0;
while(count<10)
{
++count;
</BODY>
}
if((count%5==0))
break;
else
document.write("count="+count+"<BR/>");
</SCRIPT>
</HTML>
Execute the script by opening the file in the Web Browser. If you are using Internet Explorer, click “Allow Blocked Content” to allow the script to execute and if you are using Mozilla Firefox, click allow “ActiveX Controls”.

For more details, visit the following link,
Question 21. Explain ContinueStatement in JavaScript
Answer
Like the break statement, the continue statement is used to stop the execution of the loop. However, the continue statement does not exit the loop; it executes the condition for the next iteration. Those statements are executed if the loop has any statements after the continue statement.
Write the following code,
<!DOCTYPE HTML>
<HTML>
<HEAD>
</HEAD>
<BODY>
<TITLE>Using the continue statement
</TITLE>
<H1>Using the continue statement.
</H1>
<SCRIPT type="text/javascript"> var count=0;
while(count<10)
(
</BODY>
</HTML>
}
++count;
if((count%2==0))
continue;
else
document.write("count="+count+"<BR/>");
document.write("While loop exited"):
</SCRIPT>
Execute the script by opening the file in the Web Browser. If you are using Internet Explorer, click “Allow Blocked Content” to allow the script to execute and if you are using Mozilla Firefox, click allow “ActiveX Controls”.

For more details, visit the following link,
Question 22. What is InnerHTML Property in JavaScript?
Answer
InnerHTML property can be used to modify an HTML document. InnerHTML property exists in all types of major Browsers. When you use InnerHTML, you can change the page's content without refreshing the page. This can make your Website feel quicker and more responsive to user input.
Syntax
The syntax for using InnerHTML looks like this,
document.getElementById('ID of element').innerHTML = 'Data or content';
- getElementById- getElementById refers to the HTML element using its ID.
- Data or content- Data is the new content to go into the element.
JavaScript Code
To make it work, use the following JavaScript function code on your page,
<script type="text/javascript">
function ShowMessage() {
document.getElementById('TextMessage').innerHTML = 'C-sharpCorner';
}
</script>
Now, drag and drop a Button control onto the form so that you have,
















Pranam BhatPosted Jul 6, 2021, 6:54 AM
Helpful! Good one!!!
Akshay MalthanePosted Dec 23, 2018, 9:37 PM
These questions are only for freshers, experience candidate won't face any of these simple questions. Many usefu questions are not included such as Inheritance, null undefined, use of this keyboard and many more
Razat KumarPosted Apr 3, 2018, 12:15 AM
Thanks . It is very nice
Prasham SabadraPosted Aug 23, 2016, 6:55 AM
Thanks for Sharing!
Ano MepaniPosted Aug 23, 2016, 4:46 AM
Superb article for wide audience. All JavaScript feature at one place
Anu VPosted Aug 21, 2016, 11:56 PM
Nice
Anupam SinghPosted Aug 20, 2016, 7:56 AM
Nice share @Nittin you almost touched each part of javascript.
Bhavik PatelPosted Aug 17, 2016, 6:33 PM
Huge list...
Vignesh ManiPosted Aug 17, 2016, 7:52 AM
Good one
Ramesh PalaniappanPosted Aug 17, 2016, 5:27 AM
Nice
SubashPosted Aug 17, 2016, 12:33 AM
Useful Article