If you are appearing for a technical round of interview for JavaScript, here’s a list of the top 63 interview questions with answers to help you prepare.
Last updated: Aug 24, 2021
Following are the JavaScript Data types:
isNan function returns true if the argument is not a number otherwise it is false.
Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.
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.
<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>
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.
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.
'this' keyword refers to the object from where it was called.
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.
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.
=== is called as strict equality operator which returns true when the two operands are having the same value without any type conversion.
To submit a form using JavaScript use document.form[0].submit();
Yes, JavaScript does support automatic type conversion, it is usually called type coercion, but conversion is perfectly accurate.
Type coercion and type conversion are similar except type coercion is when JavaScript automatically converts a value from one type to another (such as strings to numbers). It's also different in that it will decide how to coerce with its own set or rules. I found this example useful because it shows some interesting output behavior illustrating this coercive behavior:
const value1 = '5'; const value2 = 9; let sum = value1 + value2; console.log(sum);
In the above example, JavaScript has coerced the 9 from a number into a string and then concatenated the two values together, resulting in a string of 59. JavaScript had a choice between a string or a number and decided to use a string.
The compiler could have coerced the 5 into a number and returned a sum of 14, but it did not. To return this result, you'd have to explicitly convert the 5 to a number using the Number() method:
sum = Number(value1) + value2;
It can be done in the following way:
document.getElementById('myText').style.fontSize = '20'; // or document.getElementById('myText').className = 'anyclass';
There are two ways to read and write a file using JavaScript:
Following are looping structures 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
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);
"==" 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.
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.
In order to detect the operating system on the client machine, the navigator.platform string (property) should be used.
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.
The delete keyword is used to delete the property as well as its value.
Example:
var student= {age:20, batch:"ABC"}; delete student.age;
Undefined value means the -
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.
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>
All variables in the JavaScript are object data types.
An alert box displays only one button which is the OK button.
But a Confirmation box displays two buttons namely OK and cancel.
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.
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
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
Break statement exits from the current loop.
Continue statement continues with next statement of the loop.
They are as –
Primitive types are number and Boolean data types. Reference types are more complex types like strings and dates.
Generic objects can be created as:
var I = new object();
'typeof' is an operator which is used to return a string description of the type of a variable.
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 }
document.write("Welcome") is used to print the text – Welcome in the screen.
blur function is used to remove the focus from the specified object.
There are three types of errors:
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
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.
Properties are assigned to objects in the following way -
obj["class"] = 12; // or obj.class = 12;
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"; }
The status can be acquired as follows -
alert(document.getElementById('checkbox1').checked);
If the CheckBox will be checked, this alert will return TRUE.
The navigator.appVersion string can be used to detect the operating system on the client machine.
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.
Closure is a locally declared variable related to a function which stays in memory when the function has returned.
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();
A value can be appended to an array in the given manner -
arr[arr.length] = value;
The for-in loop is used to loop through the properties of an object.
The syntax for the for-in loop is -
for (let variableName 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.
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('anonymous function alert'); }; anon();
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>'
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.
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>
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"
This can be done by Using JavaScript extensions (runs from JavaScript Editor), example for opening of a file -
fh = fopen(getScriptPath(), 0);
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"]
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.
Example:
<script> document.write(escape("Hello? How are you!")); </script>
Output: Hello%3F%20How%20are%20you%21
he unescape() function is very important as it decodes the coded string.
It works in the following way.
Example:
<script> document.write(unescape("Hello%3F%20How%20are%20you%21")); </script>
Output: Hello? How are you!
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
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.
var myArray = [[[]]];
It declares a three dimensional array.
ECMA Script are like rules and guideline while Javascript is a scripting language used for web development.
For hiding JavaScript codes from old browsers:
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.