JavaScript Interview Questions (2021) - Javatpoint
JavaScript Interview Questions (2021) - Javatpoint
JavaScript interview questions and answers for provides a list of top 20 interview questions. The
frequently asked JavaScript interview questions with answers for beginners and professionals are
given below.
1) What is JavaScript?
Lightweight
Complementary to Java
Complementary to HTML
Open source
Cross-platform
3) Who developed JavaScript, and what was the first name of JavaScript?
JavaScript was developed by Brendan Eich, who was a Netscape programmer. Brendan Eich
developed this new scripting language in just ten days in the year September 1995. At the time of
its launch, JavaScript was initially called Mocha. After that, it was called Live Script and later known
as JavaScript.
4) List some of the advantages of JavaScript.
Interactivity is high
The function which has named at the time of definition is called a named function. For example
function msg()
{
document.writeln("Named Function");
}
msg();
Named - These type of functions contains name at the time of definition. For Example:
function display()
{
document.writeln("Named Function");
}
display();
Anonymous - These type of functions doesn't contain any name. They are declared
dynamically at runtime.
var display=function()
{
document.writeln("Anonymous Function");
}
display();
It is a function that has no name. These functions are declared dynamically at runtime using the
function operator instead of the function declaration. The function operator is more flexible than a
function declaration. It can be easily used in the place of an expression. For example:
var display=function()
{
alert("Anonymous Function is invoked");
}
display();
The variables of JavaScript represent the arguments that are passed to a function.
In JavaScript, we need closures when a variable which is defined outside the scope in reference is
accessed from some inner scope.
var num = 10;
function sum()
{
document.writeln(num+num);
}
sum();
12) If we want to return the character from a specific index which method is
used?
The JavaScript string charAt() method is used to find out a char value present at the specified index.
The index number starts from 0 and goes to n-1, where n is the length of the string. The index
value can't be a negative, greater than or equal to the length of the string. For example:
var str="Javatpoint";
document.writeln(str.charAt(4));
Netscape provided the JavaScript language. Microsoft changed the name and called it JScript to
avoid the trademark issue. In other words, you can say JScript is the same as JavaScript, but
Microsoft provides it.
A simple example of JavaScript hello world is given below. You need to place it inside the body tag
of HTML.
<script type="text/javascript">
document.write("JavaScript Hello World!");
</script>
More details.
15) What are the key differences between Java and JavaScript? / How is
JavaScript different from Java?
Java JavaScript
Java creates applications that can run in any JavaScript code can run only in the browser,
virtual machine (JVM) or browser. but it can now run on the server via Node.js.
The Java code needs to be compiled. The JavaScript code doesn't require to be
complied.
Java Objects are class-based. You can't make JavaScript Objects are prototype-based.
any program in Java without creating a
class.
Java is a Complete and Standalone language JavaScript is assigned within a web page and
that can be used in backend coding. integrates with its HTML content.
Java programs consume more memory. JavaScript code is used in HTML web pages
and requires less memory.
The file extension of the Java program is The JavaScript file extension is written as ".js"
written as ".Java" and it translates source and it is interpreted but not compiled. Every
code into bytecodes which are then browser has a JavaScript interpreter to
executed by JVM (Java Virtual Machine). execute the JS code.
I am assuming that js file name is message.js, place the following script tag inside the head tag.
<script type="text/javascript" src="message.js"></script>
More details.
BOM stands for Browser Object Model. It provides interaction with the browser. The default object
of a browser is a window. So, you can call all the functions of the window by specifying the window
or directly. The window object provides various properties like document, history, screen, navigator,
location, innerHeight, innerWidth,
DOM stands for Document Object Model. A document object represents the HTML document. It can
be used to access and change the content of HTML.
More Details: Document Object Model
The window object is created automatically by the browser that represents a window of a browser.
It is not an object of JavaScript. It is a browser object.
The window object is used to display the popup dialog box. Let's see with description.
Method Description
alert() displays the alert box containing the message with ok button.
confirm() displays the confirm dialog box containing the message with ok and cancel
button.
setTimeout() performs the action after specified time like calling function, evaluating
expressions.
More details.
The history object of a browser can be used to switch to history pages such as back and forward
from the current page or another page. There are three methods of history object.
3. history.go(number) - The number may be positive for forward, negative for backward. It
loads the given page number.
More details.
More details.
function function_name(){
//function body
}
More details.
String: The string data type represents a sequence of characters. It is written within quotes and can
be represented using a single or a double quote.
Example:
var str1 = "Hello JavaTpoint"; //using double quotes
var str2 = 'Hello Javatpoint'; //using single quotes
Number: The number data type is used to represent numeric values and can be written with or
without decimals.
Example:
var x = 5; //without decimal
var y = 5.0; //with decimal
Boolean: The Boolean data type is used to represent a Boolean value, either false or true. This data
type is generally used for conditional testing.
Example:
var x = 5;
var y = 6;
var z = 5;
(x == y) // returns false
(x == z) //returns true
BigInt: The BigInt data type is used to store numbers beyond the Number data type limitation. This
data type can store large integers and is represented by adding "n" to an integer literal.
Example:
var bigInteger = 123456789012345678901234567890;
// This is an example of bigInteger.
Undefined: The Undefined data type is used when a variable is declared but not assigned. The
value of this data type is undefined, and its type is also undefined.
Example:
var x; // value of x is undefined
var y = undefined; // You can also set the value of a variable as undefined.
Null: The Null data type is used to represent a non-existent, null, or a invalid value i.e. no value at
all.
Example:
var x = null;
Symbol: Symbol is a new data type introduced in the ES6 version of JavaScript. It is used to store
an anonymous and unique value.
Example:
var symbol1 = Symbol('symbol');
typeof: The typeof operator is used to determine what type of data a variable or operand contains.
It can be used with or without parentheses (typeof(x) or typeof x). This is mainly used in situations
when you need to process the values of different types.
Example:
typeof 10; // Returns: "number"
typeof 10.0; // Returns: "number"
typeof 2.5e-4; // Returns: "number"
typeof Infinity; // Returns: "number"
typeof NaN; // Returns: "number". Despite being "Not-A-Number"
// Strings
typeof ''; // Returns: "string"
typeof 'Welcome to JavaTpoint'; // Returns: "string"
typeof '12'; // Returns: "string". Number within quotes is typeof string
// Booleans
typeof true; // Returns: "boolean"
typeof false; // Returns: "boolean"
// Undefined
typeof undefined; // Returns: "undefined"
typeof undeclaredVariable; // Returns: "undefined"
// Null
typeof Null; // Returns: "object"
// Objects
typeof {name: "John", age: 18}; // Returns: "object"
// Arrays
typeof [1, 2, 3]; // Returns: "object"
// Functions
typeof function(){}; // Returns: "function"
In the above examples, we can see that the primitive data types can store only a single value. To
store multiple and complex values, we have to use non-primitive data types.
Object: The Object is a non-primitive data type. It is used to store collections of data. An object
contains properties, defined as a key-value pair. A property key (name) is always a string, but the
value can be any data type, such as strings, numbers, Booleans, or complex data types like arrays,
functions, and other objects.
Example:
// Collection of data in key-value pairs
var obj1 = {
x: 123,
y: "Welcome to JavaTpoint",
z: function(){
return this.x;
}
}
Array: The Array data type is used to represent a group of similar values. Every value in an array
has a numeric position, called its index, and it may contain data of any data type-numbers, strings,
Booleans, functions, objects, and even other arrays. The array index starts from 0 so that the first
array element is arr[0], not arr[1].
Example:
var colors = ["Red", "Yellow", "Green", "Orange"];
var cities = ["Noida", "Delhi", "Ghaziabad"];
alert(colors[2]); // Output: Green
alert(cities[1]); // Output: Delhi
More details.
The == operator checks equality only whereas === checks equality, and data type, i.e., a value
must be of the same type.
The innerHTML property is used to write the HTML code using JavaScript dynamically. Let's see a
simple example:
document.getElementById('mylocation').innerHTML="
<h2>This is heading using JavaScript</h2>";
More details.
The innerText property is used to write the simple text using JavaScript dynamically. Let's see a
simple example:
document.getElementById('mylocation').innerText="This is text using JavaScript";
More details.
28) How to create objects in JavaScript?
1. By object literal
3. By Object Constructor
emp={id:102,name:"Rahul Kumar",salary:50000}
More details.
1. By array literal
var emp=["Shyam","Vimal","Ratan"];
More details.
The isNan() function returns true if the variable value is not a number. For example:
function number(num) {
if (isNaN(num)) {
return "Not a Number";
}
return "Number";
}
console.log(number('1000F'));
// expected output: "Not a Number"
console.log(number('1000'));
// expected output: "Number"
3030 because 10+20 will be 30. If there is numeric value before and after +, it treats as binary +
(arithmetic operator).
function display()
{
document.writeln(10+20+"30");
}
display();
102030 because after a string all the + will be treated as string concatenation operator (not binary
+).
function display()
{
document.writeln("10"+20+30);
}
display();
33) Difference between Client side JavaScript and Server side JavaScript?
Client-side JavaScript comprises the basic language and predefined objects which are relevant to
running JavaScript in a browser. The client-side JavaScript is embedded directly by in the HTML
pages. The browser interprets this script at runtime.
The storage of cookies on the hard disk depends on the OS and the browser.
The Netscape Navigator on Windows uses a cookies.txt file that contains all the cookies. The path is
c:\Program Files\Netscape\Users\username\cookies.txt
The Internet Explorer stores the cookies on a file username@website.txt. The path is:
c:\Windows\Cookies\username@Website.txt.
For example: If you use it in a form element, it prevents it from submitting. If used in an anchor
element, it prevents it from navigating. If used in a contextmenu, it prevents it from showing or
displaying.
On the other hand, the event.stopPropagation() method is used to stop the propagation of an
event or stop the event from occurring in the bubbling or capturing phase.
The original name was Mocha, a name chosen by Marc Andreessen, founder of Netscape. In
September of 1995, the name was changed to LiveScript. In December 1995, after receiving a
trademark license from Sun, the name JavaScript was adopted.
37) How can you check if the event.preventDefault() method was used in
an element?
When we use the event.defaultPrevent() method in the event object returns a Boolean indicating
that the event.preventDefault() was called in a particular element.
38) What is the difference between undefined value and null value?
Undefined value: A value that is not defined and has no keyword is known as undefined value. For
example:
int number;//Here, a number has an undefined value.
Null value: A value that is explicitly specified by the keyword "null" is known as a null value. For
example:
String str=null;//Here, str has a null value.
39) How to set the cursor to wait in JavaScript?
The cursor can be set to wait in JavaScript by using the property "cursor". The following example
illustrates the usage:
<script>
window.document.body.style.cursor = "wait";
</script>
var myArray = [[[]]];
No, Java and JavaScript are the two different languages. Java is a robust, secured and object-
oriented programming language whereas JavaScript is a client-side scripting language with some
limitations.
Negative Infinity is a number in JavaScript which can be derived by dividing the negative number
by zero. For example:
var num=-5;
function display()
{
document.writeln(num/0);
}
display();
//expected output: -Infinity
43) What is the difference between View state and Session state?
"View state" is specific to a page in a session whereas "Session state" is specific to a user or browser
that can be accessed across all pages in the web application.
44) What are the pop-up boxes available in JavaScript?
Alert Box
Confirm Box
Prompt Box
<script type="text/javascript">
function msg(){
alert("Hello Alert Box");
}
</script>
<input type="button" value="click" onclick="msg()"/>
<script type="text/javascript">
function msg(){
var v= confirm("Are u sure?");
if(v==true){
alert("ok");
}
else{
alert("cancel");
}
}
</script>
<input type="button" value="delete record" onclick="msg()"/>
<script type="text/javascript">
function msg(){
var v= prompt("Who are you?");
alert("I am "+v);
}
</script>
<input type="button" value="click" onclick="msg()"/>
The navigator.appVersion string can be used to detect the operating system on the client
machine.
Let's see the JavaScript code to submit the form by clicking the link.
<form name="myform" action="index.php">
Search: <input type='text' name='query' />
<a href="javascript: submitform()">Search</a>
</form>
<script type="text/javascript">
function submitform()
{
document.myform.submit();
}
</script>
<script type="text/javascript">
document.body.bgColor="pink";
</script>
By the help of try/catch block, we can handle exceptions in JavaScript. JavaScript supports try,
catch, finally and throw keywords for exception handling.
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
Test it Now
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-
mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
Test it Now
The this keyword is a reference variable that refers to the current object. For example:
var address=
{
company:"Javatpoint",
city:"Noida",
state:"UP",
fullAddress:function()
{
return this.company+" "+this.city+" "+this.state;
}
};
var fetch=address.fullAddress();
document.writeln(fetch);
JavaScript didn't show any error message in a browser. However, these mistakes can affect the
output. The best practice to find out the error is to debug the code. The code can be debugged
easily by using web browsers like Google Chrome, Mozilla Firebox.
JavaScript debugger keyword sets the breakpoint through the code itself. The debugger stops the
execution of the program at the position it is applied. Now, we can start the flow of execution
manually. If an exception occurs, the execution will stop again on that particular line.. For example:
function display()
{
x = 10;
y = 15;
z = x + y;
debugger;
document.write(z);
document.write(a);
}
display();
The JavaScript strict mode is used to generates silent errors. It provides "use strict"; expression to
enable the strict mode. This expression can only be placed as the first statement in a script or a
function. For example:
"use strict";
x=10;
console.log(x);
57) What is the use of Math object in JavaScript?
The JavaScript math object provides several constants and methods to perform a mathematical
operation. Unlike date object, it doesn't have constructors. For example:
function display()
{
document.writeln(Math.random());
}
display();
The JavaScript date object can be used to get a year, month and day. You can display a timer on
the webpage by the help of JavaScript date object.
function display()
{
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
}
display();
The JavaScript number object enables you to represent a numeric value. It may be integer or
floating-point. JavaScript number object follows the IEEE standard to represent the floating-point
numbers.
function display()
{
var x=102;//integer value
var y=102.7;//floating point value
var z=13e4;//exponent value, output: 130000
var n=new Number(16);//integer value by number object
document.write(x+" "+y+" "+z+" "+n);
}
display();
The JavaScript Boolean is an object that represents value in two states: true or false. You can create
the JavaScript Boolean object by Boolean() constructor.
function display()
{
document.writeln(10<20);//true
document.writeln(10<5);//false
}
display();
The JavaScript TypedArray object illustrates an array like a view of an underlying binary data buffer.
There is any number of different global properties, whose values are TypedArray constructors for
specific element types.
function display()
{
var arr1= [1,2,3,4,5,6,7,8,9,10];
arr1.copyWithin(2) ;
document.write(arr1);
}
display();
The JavaScript Set object is used to store the elements with unique values. The values can be of any
type i.e. whether primitive values or object references. For example:
function display()
{
var set = new Set();
set.add("jQuery");
set.add("AngularJS");
set.add("Bootstrap");
for (let elements of set) {
document.writeln(elements+"<br>");
}
}
display();
The JavaScript WeakSet object is the type of collection that allows us to store weakly held objects.
Unlike Set, the WeakSet are the collections of objects only. It doesn't contain the arbitrary values.
For example:
function display()
{
var ws = new WeakSet();
var obj1={};
var obj2={};
ws.add(obj1);
ws.add(obj2);
//Let's check whether the WeakSet object contains the added object
document.writeln(ws.has(obj1)+"<br>");
document.writeln(ws.has(obj2));
}
display()
The JavaScript Map object is used to map keys to values. It stores each element as key-value pair. It
operates the elements such as search, update and delete on the basis of specified key. For example:
function display()
{
var map=new Map();
map.set(1,"jQuery");
map.set(2,"AngularJS");
map.set(3,"Bootstrap");
document.writeln(map.get(1)+"<br>");
document.writeln(map.get(2)+"<br>");
document.writeln(map.get(3));
}
display();
The JavaScript WeakMap object is a type of collection which is almost similar to Map. It stores each
element as a key-value pair where keys are weakly referenced. Here, the keys are objects and the
values are arbitrary values. For example:
function display()
{
var wm = new WeakMap();
var obj1 = {};
var obj2 = {};
var obj3= {};
wm.set(obj1, "jQuery");
wm.set(obj2, "AngularJS");
wm.set(obj3,"Bootstrap");
document.writeln(wm.has(obj2));
}
display();
66) What are the falsy values in JavaScript, and how can we check if a
value is falsy?
Those values which become false while converting to Boolean are called falsy values.
const falsyValues = ['', 0, null, undefined, NaN, false];
We can check if a value is falsy by using the Boolean function or the Double NOT operator (!!).
Example 1:
hoistedVariable = 12;
console.log(hoistedVariable); // outputs 12 even when the variable is declared after it is initializ
var hoistedVariable;
Example2:
hoistedFunction(); // Outputs " Welcome to JavaTpoint " even when the function is declared af
function hoistedFunction(){
console.log(" Welcome to JavaTpoint ");
}
Example3:
// Hoisting in a local scope
function doSomething(){
x = 11;
console.log(x);
var x;
}
doSomething(); // Outputs 11 since the local variable "x" is hoisted inside the local scope