Top 60+ JavaScript Interview Questions and Answers (2025)

JavaScript interview questions and their corresponding answers offer a compilation of the 20 most prominent inquiries. Below, you will find a selection of commonly posed JavaScript interview questions along with their answers, tailored for both novice and experienced individuals.

1) What is JavaScript?

JavaScript is recognized as a scripting language. It differs from the Java programming language in several aspects. As an object-oriented, lightweight, and cross-platform interpreted language, JavaScript is extensively utilized for client-side validation tasks. The JavaScript interpreter, which is integrated within the web browser, takes on the role of converting JavaScript code so that it can be executed in the browser environment. For further information, please refer to additional details.

To read more: JavaScript Tutorial

2) List some features of JavaScript.

Some of the features of JavaScript are:

  • Lightweight
  • Interpreted programming language
  • Good for the applications which are network-centric
  • Complementary to Java
  • Complementary to HTML
  • Open source
  • Cross-platform

To read more: Features of JavaScript

3) Who developed JavaScript, and what was the first name of JavaScript?

JavaScript was created by Brendan Eich, a programmer at Netscape. He crafted this innovative scripting language in a mere ten days during September 1995. Upon its release, the language was first referred to as Mocha. Subsequently, it was renamed to Live Script before finally becoming known as JavaScript.

To read more: Who Created JavaScript

4) List some of the advantages of JavaScript.

Some of the advantages of JavaScript are:

  • Server interaction is less
  • Feedback to the visitors is immediate
  • Interactivity is high
  • Interfaces are richer
  • 5) List some of the disadvantages of JavaScript.

Some of the disadvantages of JavaScript are:

  • No support for multithreading
  • No support for multiprocessing
  • Reading and writing of files is not allowed
  • No support for networking applications.
  • 6) Define a named function in JavaScript.

A function that is assigned a name during its definition is referred to as a named function. For instance,

Example

function msg()

{

  document.writeln("Named Function");

}

msg();

For additional information: How to create a function in JavaScript

7) Name the types of functions

The types of function are:

Example

function display()

{

  document.writeln("Named Function");

}

display();
Example

var display=function()

{

  document.writeln("Anonymous Function");

}

display();
  • Named - These type of functions contains name at the time of definition. For Example:
  • Anonymous - These type of functions doesn't contain any name. They are declared dynamically at runtime.

To read more: JavaScript Functions

8) Define anonymous function

This is an unnamed function. Such functions are created dynamically during execution using the function operator rather than through traditional function declarations. The function operator offers greater flexibility compared to a standard function declaration. It can be seamlessly utilized in expressions. For instance:

Example

var display=function()

{

  alert("Anonymous Function is invoked");

}

display();

To read more: Anonymous Function in JavaScript

9) Can an anonymous function be assigned to a variable?

Indeed, it is possible to assign an unnamed function to a variable.

10) In JavaScript what is an argument object?

In JavaScript, variables serve as the representations of the parameters that are provided to a function.

11) Define closure.

In JavaScript, closures are necessary when a variable that is declared outside of a certain scope is accessed from within a nested scope.

Example

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 charAt method in JavaScript is utilized to retrieve the character located at a specific index within a string. The indexing begins at 0 and extends to n-1, where n represents the total number of characters in the string. It is important to note that the index must not be negative and cannot be equal to or exceed the length of the string. For instance:

Example

var str="Example";  

document.writeln(str.charAt(4));

13) What is the difference between JavaScript and JScript?

Netscape introduced the JavaScript programming language. To prevent trademark conflicts, Microsoft rebranded it as JScript. Essentially, JScript can be considered equivalent to JavaScript, with the distinction that it is offered by Microsoft.

14) How to write a hello world example of JavaScript?

Below is a straightforward illustration of a JavaScript "Hello, World!" program. It is necessary to insert this code within the body tag of your HTML document.

Example

<script type="text/javascript">

document.write("JavaScript Hello World!");

</script>

To read more: Hello World Program in JavaScript

15) What are the key differences between Java and JavaScript? / How is JavaScript different from Java?

JavaScript is a nimble programming language, often referred to as a scripting language, that was created by Netscape, Inc. Its primary purpose is to enhance the interactivity of web pages. It is important to note that it is not associated with the Java platform. Below is a compilation of essential distinctions between Java and JavaScript:

Here is a compilation of essential distinctions between Java and JavaScript:

  • Type of Language: Java is a statically typed, object-oriented programming language, whereas JavaScript is a dynamically typed, prototype-based scripting language. This fundamental difference impacts how variables are declared and managed within the respective languages.
  • Execution Environment: Java applications are typically executed on the Java Virtual Machine (JVM), which allows them to run on any platform that has a JVM installed. In contrast, JavaScript is primarily executed in web browsers, enabling interactive features on websites, although it can also run on servers via environments such as Node.js.
  • Syntax and Structure: While both languages share a syntax influenced by C, Java employs a more rigid structure requiring explicit declarations and strict typing. JavaScript, however, offers a more flexible syntax with less emphasis on strict type definitions.
  • Concurrency Model: Java uses multi-threading to handle concurrent tasks, allowing multiple threads to run simultaneously within a program. JavaScript, on the other hand, employs an event-driven, single-threaded model, utilizing asynchronous programming through callbacks, promises, and async/await functions to manage tasks.
  • Inheritance: Java supports class-based inheritance, where classes are defined and objects are created as instances of these classes. JavaScript utilizes prototype-based inheritance, allowing objects to inherit directly from other objects without the need for class definitions.
  • Use Cases: Java is commonly used for building large-scale enterprise applications, mobile applications (especially Android), and server-side development. JavaScript, however, is predominantly used for enhancing user interfaces on the web, enabling dynamic content, and developing web applications.
  • Libraries and Frameworks: Java boasts a wealth of well-established frameworks such as Spring and Hibernate that facilitate enterprise development. Meanwhile, JavaScript has a plethora of libraries and frameworks like React, Angular, and Vue.js that aid in front-end development and enhance user experience.
  • Community and Ecosystem: Both languages have extensive communities and ecosystems. Java has a long-standing presence in enterprise environments, backed by a large pool of resources and community support. JavaScript, with its rapid evolution in web technology, has garnered a vibrant community focused on modern web development practices.

These differences highlight the unique characteristics and applications of Java and JavaScript, allowing developers to choose the appropriate language based on their project requirements and goals.

Java JavaScript
Java is a complete and strongly typed programming language used for backend coding. In Java, variables must be declared first to use in the program, and the type of a variable is checked at compile-time. JavaScript is a weakly typed, lightweight programming language (most commonly known as scripting language) and has more relaxed syntax and rules.
Java is an object-oriented programming (OOPS) language or structured programming languages such as C, C++, or .Net. JavaScript is a client-side scripting language, and it doesn't fully support the OOPS concept. It resides inside the HTML documents and is used to make web pages interactive (not achievable with simple HTML).
Java creates applications that can run in any virtual machine (JVM) or browser. JavaScript code can run only in the 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 any program in Java without creating a class. JavaScript Objects are prototype-based.
Java is a Complete and Standalone language that can be used in backend coding. JavaScript is assigned within a web page and 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 written as ".Java" and it translates source code into bytecodes which are then executed by JVM (Java Virtual Machine). The JavaScript file extension is written as ".js" and it is interpreted but not compiled. Every browser has a JavaScript interpreter to execute the JS code.
Java supports multithreading. JavaScript doesn't support multithreading.
Java uses a thread-based approach to concurrency. JavaScript uses an event-based approach to concurrency.

To read more: Difference Between Java and JavaScript

16) How to use external JavaScript file?

I will assume that the JavaScript file is named message.js; therefore, you should insert the following script tag within the head section.

Example

<script type="text/javascript" src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image"></script>

17) Is JavaScript case sensitive language?

Indeed, JavaScript is a language that differentiates between uppercase and lowercase letters. For instance:

Example

Var msg = "JavaScript is a case-sensitive language"; //Here, var should be used to declare a variable

function display() 

{

document.writeln(msg); // It will not display the result.

} 

display();

To read more: Is JavaScript case sensitive

18) What is BOM?

BOM refers to the Browser Object Model. It facilitates interaction with the web browser. The primary object associated with a browser is the window. Therefore, you can invoke all the functions of the window either by explicitly mentioning the window or by calling them directly. The window object offers numerous properties, including document, history, screen, navigator, location, innerHeight, and innerWidth.

To read more: BOM (Browser Object Model)

19) What is DOM? What is the use of document object?

DOM, which stands for Document Object Model, is a representation of the HTML document in an object-oriented manner. This document object allows developers to interact with and modify the content contained within HTML.

To read more: DOM (Document Object Model)

20) What is the use of window object?

The window object is instantiated automatically by the web browser to symbolize a browser window. It does not qualify as a JavaScript object; rather, it is classified as a browser object.

The window object serves the purpose of presenting a popup dialog box. Let us explore this further with an explanation.

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.
prompt() displays a dialog box to get input from the user.
open() opens the new window.
close() closes the current window.
setTimeout() performs the action after specified time like calling function, evaluating expressions.

To read more: Javascript Window Object

21) What is the use of history object?

The history object of a browser can be used to switch to history pages such as back and forward from the current page or another page. There are three methods of history object.

  • history.back - It loads the previous page.
  • history.forward - It loads the next page.
  • history.go(number) - The number may be positive for forward, negative for backward. It loads the given page number.

To read more: Javascript History Object

22) How to write a comment in JavaScript?

In JavaScript, there exist two distinct forms of comments.

  • Single Line Comment: This type is denoted by // (two forward slashes)
  • Multi-Line Comment: This is indicated by the slash followed by an asterisk, formatted as / write comment here /

To read more: JavaScript Comments

23) How to create a function in JavaScript?

To define a function in JavaScript, adhere to the syntax outlined below.

Example

function function_name(){

//function body

}

To read more: JavaScript Function

24) What are the different data types present in JavaScript?

JavaScript encompasses two categories of data types:

  • Primitive data types
  • Non-Primitive data types

Primitive data types

The primitive data types are as follows:

String: The string data type denotes a collection of characters. It is enclosed in quotes and can be expressed using either single or double quotation marks.

Example:

Example

var str1 = "Hello World"; //using double quotes

var str2 = 'Hello World'; //using single quotes

Number: The numeric data type is utilized to denote numerical values and can be expressed either with or without decimal points.

Example:

Example

var x = 5; //without decimal

var y = 5.0; //with decimal

Boolean: The Boolean data type serves to signify a Boolean value, which can either be false or true. This particular data type is typically employed for evaluating conditions.

Example:

Example

var x = 5;

var y =  6;

var z =  5;

(x == y) // returns false

(x == z) //returns true

BigInt: The BigInt data type is designed to accommodate numbers that exceed the limitations of the standard Number data type. This type allows for the storage of large integer values and is denoted by appending "n" to an integer literal.

Example:

Example

var bigInteger =  123456789012345678901234567890;

// This is an example of bigInteger.

Undefined: The Undefined data type is utilized in scenarios where a variable has been declared but remains unassigned. The value associated with this data type is undefined, and it is classified as having an undefined type.

Example:

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 utilized to signify a value that is non-existent, null, or invalid, indicating that there is absolutely no value present.

Example:

Example

var  x = null;

Symbol: The Symbol data type was introduced in the ES6 iteration of JavaScript. It serves the purpose of holding a unique and anonymous value.

Example:

Example

var symbol1 = Symbol('symbol');

typeof: The typeof operator serves the purpose of identifying the data type that a variable or operand holds. It can be employed with or without parentheses (for instance, typeof(x) or typeof x). This operator is particularly useful in scenarios where it is necessary to handle values of various types.

Example:

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 our tutorial';  // 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"

Non-Primitive data types

In the examples provided earlier, it is evident that primitive data types are capable of holding only one value at a time. To accommodate multiple values or more intricate data structures, it is necessary to utilize non-primitive data types.

The non-primitive data types are as follows:

Object: An Object represents a non-primitive data type. It serves the purpose of holding collections of data. An object is comprised of properties, which are established as key-value pairs. The property key (or name) is consistently a string; however, the corresponding value can be of any data type, including strings, numbers, Booleans, or more intricate data types such as arrays, functions, and other objects.

Example:

Example

// Collection of data in key-value pairs

var obj1 = {

   x:  123,

   y:  "Welcome to our tutorial",

   z: function(){

      return this.x;

   }

}

Array: The Array data structure is utilized to hold a collection of similar values. Each value within an array is assigned a numeric position known as its index, and it can store data of any type, including numbers, strings, Booleans, functions, objects, and even nested arrays. The indexing of arrays begins at 0, which means that the initial element in the array is accessed using arr[0], rather than arr[1].

Example:

Example

var colors = ["Red", "Yellow", "Green", "Orange"];

var cities = ["Noida", "Delhi", "Ghaziabad"];

alert(colors[2]);   // Output: Green

alert(cities[1]);   // Output: Delhi

To read more: JavaScript Data Types

25) What is the difference between == and ===?

The == operator is used solely to evaluate equality, while the === operator assesses both equality and the data type. In other words, for two values to be considered equal using ===, they must not only be equivalent but also share the same data type.

For further reading: A guide on comparing objects in JavaScript

26) How to write HTML code dynamically using JavaScript?

The innerHTML attribute allows for the dynamic generation of HTML content through JavaScript. Consider the following straightforward example:

Example

document.getElementById('mylocation').innerHTML="<h2>This is heading using JavaScript</h2>";

To read more: JavaScript innerHTML

27) How to write normal text code using JavaScript dynamically?

The innerText property enables the dynamic insertion of plain text using JavaScript. Here’s a straightforward example:

Example

document.getElementById('mylocation').innerText="This is text using JavaScript";

To read more: JavaScript innerText

28) How to create objects in JavaScript?

There are 3 ways to create an object in JavaScript.

  • By object literal
  • By creating an instance of Object
  • By Object Constructor

Let’s examine a straightforward example of how to establish an object utilizing an object literal.

Example

emp={id:102,name:"Rahul Kumar",salary:50000}

To read more: JavaScript objects

29) How to create an array in JavaScript?

There are 3 ways to create an array in JavaScript.

  • By array literal
  • By creating an instance of Array
  • By using an Array constructor

Let us examine a straightforward example of how to construct an array utilizing an object literal.

Example

var emp=["Shyam","Vimal","Ratan"];

To read more: JavaScript Array

30) What does the isNaN function?

The isNan function yields a true result when the value of the variable is not a numeric value. For instance:

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"

To read more: JavaScript NaN Function

31) What is the output of 10+20+"30" in JavaScript?

3030 arises from the addition of 10 and 20, resulting in 30. When there is a numeric value on both sides of the + symbol, it is interpreted as a binary + (arithmetic operator).

Example

function display()

{

  document.writeln(10+20+"30");

}

display();

32) What is the output of "10"+20+30 in JavaScript?

102030, as any characters following a string will cause all the + symbols to be interpreted as the string concatenation operator (rather than as a binary addition operator).

Example

function display()

{

  document.writeln("10"+20+30);

}

display();

33) Difference between Client side JavaScript and Server side JavaScript?

Client-side JavaScript includes the fundamental language features and built-in objects essential for executing JavaScript within a web browser. This client-side JavaScript code is incorporated directly into HTML documents. The web browser processes this script during runtime.

Server-side JavaScript shares similarities with client-side JavaScript. It utilizes a pertinent version of JavaScript designed to execute on a server. The JavaScript code intended for server-side use is only deployed following a compilation process.

For further reading: Distinction between Server-side Scripting and Client-side Scripting

34) In which location cookies are stored on the hard disk?

The manner in which cookies are stored on a hard drive is contingent upon both the operating system and the web browser in use.

On Windows, the Netscape Navigator application utilizes a cookies.txt file that stores all the cookies. The file can be found at the following location: c:\Program Files\Netscape\Users\username\cookies.txt

Internet Explorer saves cookies in a file named [email protected] The corresponding path for this file is: c:\Windows\Cookies\[email protected]

35) What's the difference between event.preventDefault and event.stopPropagation methods in JavaScript?

In JavaScript, the method event.preventDefault is utilized to stop the standard behavior associated with an element from occurring.

For instance: When utilized within a form element, it stops the form from being submitted. When applied to an anchor element, it inhibits the navigation process. In the case of a context menu, it prevents it from appearing or being displayed.

Conversely, the event.stopPropagation function is utilized to prevent the event from propagating, effectively halting the event during either the bubbling or capturing phase.

For further information: Distinction between the preventDefault and stopPropagation methods

36) What is the real name of JavaScript?

Initially, the programming language was referred to as Mocha, a title selected by Marc Andreessen, the founder of Netscape. In September 1995, this designation was modified to LiveScript. Subsequently, in December 1995, following the acquisition of a trademark license from Sun, the name JavaScript was officially embraced.

37) How can you check if the event.preventDefault method was used in an element?

The event.defaultPrevented property within the event object provides a Boolean value that indicates whether the event.preventDefault method has been invoked on a specific element.

For additional information: jQuery event.preventDefault function

38) What is the difference between undefined value and null value?

Undefined Value: An undefined value refers to a situation where a variable has not been assigned a specific value and lacks an associated keyword. For instance:

Example

int number;//Here, a number has an undefined value.

Null Value: A value that is specifically defined using the keyword "null" is referred to as a null value. For instance:

Example

String str=null;//Here, str has a null value.

For additional information: Distinction between Null and Undefined

39) How to set the cursor to wait in JavaScript?

In JavaScript, the cursor's behavior can be modified to indicate a waiting state by utilizing the "cursor" property. The example below demonstrates how this can be implemented:

Example

<script>

window.document.body.style.cursor = "wait"; 

</script>

40) What is this [[]]?

This is a three-dimensional array.

Example

var myArray = [[[]]];

41) Are Java and JavaScript same?

No, Java and JavaScript are distinct programming languages. Java is a strong, secure, and object-oriented language, while JavaScript functions as a client-side scripting language with certain constraints.

To read more: Java vs JavaScript

42) What is negative infinity?

In JavaScript, Negative Infinity is a numerical value that can be obtained by performing division of a negative number by zero. For instance:

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" pertains to a particular page within a session, while "Session state" relates to a user or browser, allowing access across all pages within the web application.

44) What are the pop-up boxes available in JavaScript?

  • Alert Box
  • Confirm Box
  • Prompt Box
  • Example of alert in JavaScript

    Example
    
    <script type="text/javascript">
    
    function msg(){
    
     alert("Hello Alert Box");
    
    }
    
    </script>
    
    <input type="button" value="click" onclick="msg()"/>
    

To read more: JavaScript alert

Example of confirm in JavaScript

Example

<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()"/>

To read more: JavaScript Confirm

Example of prompt in JavaScript

Example

<script type="text/javascript">

function msg(){

var v= prompt("Who are you?");

alert("I am "+v);



}

</script>



<input type="button" value="click" onclick="msg()"/>

To read more: JavaScript prompt dialog box

45) How can we detect OS of the client machine using JavaScript?

The string navigator.appVersion can be utilized to identify the operating system present on the client device.

46) How to submit a form using JavaScript by clicking a link?

Let’s examine the JavaScript code that enables the submission of a form when a link is clicked.

Example

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

To read more: How to Click Link Using JavaScript

47) Is JavaScript faster than ASP script?

Indeed, this is because it does not necessitate the support of a web server for its execution.

48) How to change the background color of HTML document using JavaScript?

Example

<script type="text/javascript">

document.body.bgColor="pink";

</script>

49) How to handle exceptions in JavaScript?

Utilizing the try/catch block allows us to manage exceptions within JavaScript. The language provides the keywords try, catch, finally, and throw specifically for the purpose of exception handling.

To read more: Exception Handling in JavaScript

50) How to validate a form in JavaScript?

Example

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

To read more: JavaScript form validation .

51) How to validate email in JavaScript?

Example

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

To read more: JavaScript Email validation .

52) What is this keyword in JavaScript?

The keyword this serves as a reference variable that points to the object that is currently being manipulated. For instance:

Example

var address=  

{  

company:"Example",  

city:"Noida",  

state:"UP",  

fullAddress:function()  

{  

return this.company+" "+this.city+" "+this.state;  

}  

};  

var fetch=address.fullAddress();  

document.writeln(fetch);

To read more: JavaScript this keyword

53) What is the requirement of debugging in JavaScript?

JavaScript may not display any error notifications within a browser. Nonetheless, these errors can significantly impact the results produced by your code. A recommended approach to identify these issues is to perform debugging. This process can be conveniently carried out using web browsers such as Google Chrome and Mozilla Firefox.

For the purpose of debugging, we have several methods at our disposal:

  • Utilizing the console.log function
  • Employing the debugger keyword

To read more: JavaScript Debugging

54) What is the use of debugger keyword in JavaScript?

The JavaScript debugger keyword allows developers to set breakpoints directly within the code. When invoked, the debugger halts the program's execution at the point where it is placed. This enables us to manually control the flow of execution. In the event that an exception is thrown, execution will also pause at the specific line where the error occurred. For instance:

Example

function display()

{

x = 10;  

y = 15;  

z = x + y;  

debugger;  

document.write(z);  

document.write(a);   

}   

display();

To read more: How to debug JavaScript

55) What is the role of a strict mode in JavaScript?

The strict mode in JavaScript is designed to create silent errors. To activate strict mode, the expression "use strict"; must be used. This expression is permitted solely as the initial statement within a script or function. For instance:

Example

"use strict";  

x=10;  

console.log(x);

To read more: JavaScript Strict Mode

57) What is the use of Math object in JavaScript?

The JavaScript Math object offers a variety of constants and functions that enable users to execute mathematical calculations. In contrast to the Date object, it lacks any constructors. For instance:

Example

function display()

{

  document.writeln(Math.random());

}

display();

To read more: JavaScript Math

58) What is the use of a Date object in JavaScript?

The JavaScript Date object is capable of retrieving the year, month, and day. By utilizing the JavaScript Date object, you can present a timer on a webpage.

Example

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

To read more: JavaScript Date Object

59) What is the use of a Number object in JavaScript?

The number object in JavaScript allows for the representation of numeric values. This can include both integers and floating-point numbers. The JavaScript number object adheres to the IEEE standard for the representation of floating-point values.

Example

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

To read more: JavaScript Number Object

60) What is the use of a Boolean object in JavaScript?

The JavaScript Boolean is a data type that signifies one of two possible values: true or false. You can instantiate the JavaScript Boolean object using the Boolean constructor.

Example

function display()

{

document.writeln(10<20);//true  

document.writeln(10<5);//false   

}   

display();

To read more: JavaScript Boolean

61) What is the use of a TypedArray object in JavaScript?

The JavaScript TypedArray object represents an array that serves as a view over an underlying binary data buffer. There exists a variety of global properties, each corresponding to TypedArray constructors for distinct element types.

Example

function display()

{

var arr1= [1,2,3,4,5,6,7,8,9,10];   

       arr1.copyWithin(2) ; 

       document.write(arr1);  

}

display();

To read more: JavaScript TypedArray

62) What is the use of a Set object in JavaScript?

The Set object in JavaScript is designed to hold elements that are unique in value. The values contained in a Set can be of any data type, including both primitive types and references to objects. For instance:

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

To read more: JavaScript Set

63) What is the use of a WeakSet object in JavaScript?

The JavaScript WeakSet object represents a collection that enables us to maintain weak references to objects. In contrast to a Set, a WeakSet exclusively contains objects, and it does not accommodate arbitrary values. For instance:

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

To read more: JavaScript WeakSet Object

64) What is the use of a Map object in JavaScript?

The Map object in JavaScript serves the purpose of associating keys with corresponding values. It retains every element in the form of key-value pairs. Operations such as searching, updating, and deleting elements are performed based on the designated key. For instance:

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

To read more: JavaScript Map

65) What is the use of a WeakMap object in JavaScript?

The WeakMap object in JavaScript represents a collection that closely resembles the Map structure. It holds each entry as a pair of key and value, with the distinction that the keys are weakly referenced. In this case, the keys must be objects, while the values can be any type of data. For instance:

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

To read more: JavaScript WeakMap Object

66) What are the falsy values in JavaScript, and how can we check if a value is falsy?

Values that evaluate to false when transformed into Boolean are known as falsy values.

Example

const falsyValues = ['', 0, null, undefined, NaN, false];

To determine if a value is considered falsy, we can utilize either the Boolean function or the Double NOT operator (!!).

67) What do you understand by hoisting in JavaScript?

Hoisting refers to the inherent behavior of JavaScript whereby all declarations of variables and functions are relocated to the top of their containing scope. To put it simply, hoisting is a mechanism through which variables and functions are elevated to the beginning of their respective scopes, regardless of where they are originally defined. These scopes can either be local or global in nature.

Example 1:

Example

hoistedVariable = 12;

console.log(hoistedVariable); // outputs 12 even when the variable is declared after it is initialized	

var hoistedVariable;

Example2:

Example

hoistedFunction();  // Outputs " Welcome to our tutorial " even when the function is declared after calling

function hoistedFunction(){ 

  console.log(" Welcome to our tutorial ");

}

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

To read more: Hoisting in JavaScript

JavaScript MCQ

1) Which of the following statement is true?

  • If onKeyDown returns false, the key-up event is canceled.
  • If onKeyDown returns false, the key-press event is canceled.
  • If onKeyPress returns false, the key-down event is canceled.
  • If onKeyPress returns false, the key-up event is canceled.

2) Which of the following statement shows the primary difference between JavaScript and Java?

  • There is no difference between JavaScript and Java.
  • Functions are considered as fields.
  • Variables are specific.
  • Functions are values, and there is no such distinction between methods and fields.

Response: D is the accurate choice. It is well-established that Java is classified as an object-oriented programming (OOP) language, whereas JavaScript is categorized as an OOP scripting language. The primary distinction between JavaScript and Java lies in the fact that functions in JavaScript are treated as values, and there is no clear separation between methods and fields.

3) Which of the following syntaxes is correct for instantiating a RegExp object?

Example

1. var txt=new RegExp(pattern,attributes);

2. var txt=/pattern/attributes;
  • Only 1 syntax
  • Only 2 syntax
  • Both 1 and 2 syntax
  • None of the above

Response: C: Both statements are accurate and can be utilized for the creation of a RegExp object.

4) Which of the following statement specifies the meaning of Augmenting classes?

  • Objects inherit prototype properties even in a dynamic state.
  • Objects inherit prototype properties only in a dynamic state.
  • Objects inherit prototype properties in the static state.
  • An object doesn't inherit prototype properties in the static state.

Response: A: "Objects inherit properties from their prototypes, even while in a dynamic context" is the accurate response.

5) If para1 is the DOM object for a paragraph, which of the following would be the correct syntax to change the text within the paragraph?

  • para1="New Text"
  • firstChild.nodeValue= "New Text";
  • value="New Text";
  • nodeValue="New Text";

Response: C: "para1.value = 'New Text';" represents the accurate syntax for modifying the text contained within the paragraph.

6) Which of the following is used to define the behavior of the instances present of a class inside a method?

  • Method
  • Classes
  • Interfaces
  • Classes and Interfaces

Response: B: "Classes" is indeed the correct option. The behavior of a class is defined within the class itself and is consistently shared across all its instances.

7) Which of the following statement is true in the case of the property of the JSON method?

  • A JSON method can be invoked manually as object.JSON
  • A JSON method is invoked automatically by the JSON.stringify method
  • A JSON method is automatically invoked by the compiler.
  • A JSON method cannot be invoked in any form.

Response: The appropriate choice is B. The JSON function is predominantly utilized for transferring data between a web server and a client. When transmitting data to a web server, it is essential that the data is formatted as a string. In such instances, json.stringify is employed to transform a JavaScript object into a string format.

8) Which of the following statement is true if class B can extend another class A?

  • A is the superclass, and B is the subclass.
  • B is the superclass, and A is the subclass.
  • Both A and B are the superclass.
  • Both A and B are subclass.

Response: A: "A is the superclass and B is the subclass" is the accurate response. A class is referred to as a superclass when it has the capability to establish a subclass. Subclasses are often described as extensions or derivatives of a superclass.

9) Which of the following is the correct syntax of the eval function?

  • [objectName.]eval(numeric)
  • [EvalName.]eval(string)
  • [EvalName.]eval(numeric)
  • [objectName.]eval(string)

The accurate choice is D. The eval function serves the purpose of assessing or executing a given argument. When the argument consists of an expression, the eval function processes that expression. Conversely, if the argument includes one or several JavaScript statements, the eval function carries out the execution of those statements.

10) What will be the result of executing the following JavaScript code?

Example

const obj1 = 

{  

	a: 10,  

  	b: 15,  

  	c: 18  

};  

const obj2 = Object.assign({c: 11, d: 12}, obj1);  

console.log(obj2.c, obj2.d);
  • 10, 12
  • 11, 12
  • Undefined
  • Error

Response: B: 11, 12 is the accurate response. The Object.assign function is utilized to transfer the properties and values from one object to another.

Input Required

This code uses input(). Please provide values below: