TutorialStudyMite

JavaScript Interview Questions – Frequently Asked

VVaaruni Agarwal16 min read
Beginner friendly

Track completion, mastery, and revision.

JavaScript is the cornerstone of modern web development. Originally created by Brendan Eich in 1995, it has evolved from a simple client-side scripting language into a powerful, high-level, multi-paradigm language capable of running on both client browsers and backend servers.

Whether you are preparing for a frontend role or a full-stack position, these frequently asked JavaScript interview questions will help you solidify your core knowledge.


1. What is JavaScript?

JavaScript is a lightweight, interpreted, or Just-In-Time (JIT) compiled programming language with first-class functions. While it is best known as the scripting language for web pages, many non-browser environments also use it, such as Node.js. It is a multi-paradigm language supporting object-oriented, imperative, and declarative (e.g., functional) programming styles.


2. What are some key features of JavaScript?

  • Lightweight and Interpreted: It runs directly in the browser without requiring a heavy compilation step beforehand.
  • Single-threaded: It executes code sequentially but handles asynchronous operations efficiently using the Event Loop.
  • Cross-platform: It works seamlessly across different operating systems and browsers.
  • Complementary to HTML and CSS: It integrates perfectly with HTML and CSS to create dynamic, interactive web pages.
  • Prototypal Inheritance: Objects can inherit properties directly from other objects.

3. What are the advantages of JavaScript?

  • Reduced Server Load: Basic validation and logic can be performed on the client side before sending data to the server, saving bandwidth.
  • Immediate Feedback: Users don't have to wait for a full page reload to see if they made a mistake in a form.
  • Rich Interfaces: You can create drag-and-drop components, sliders, and interactive maps to enhance user experience.
  • Interactivity: It allows developers to build highly dynamic, event-driven web applications.

4. What are the disadvantages of JavaScript?

  • Client-Side Security: Since the code executes on the client's machine, it can be viewed, modified, or exploited if not properly secured.
  • No Multithreading: JavaScript does not natively support concurrent multithreading out of the box (though Web Workers help mitigate this).
  • No Direct File Access: For security reasons, client-side JavaScript cannot read or write files directly to the user's hard drive.

5. Who created JavaScript?

JavaScript was created by Brendan Eich in 1995 while working at Netscape Communications. It was famously developed in just 10 days under the original name Mocha, later renamed to LiveScript, and finally JavaScript.


6. What are the different types of functions available in JavaScript?

JavaScript supports several ways to define functions. The two most fundamental types are:

Named Functions

These functions are defined with a specific name, allowing them to be called recursively or referenced easily.

function display() {  
  console.log("Welcome to StudyMite!");  
}  

Anonymous Functions

These functions do not have a name. They are often declared dynamically at runtime and assigned to variables or passed as arguments.

var display = function() {  
  console.log("Welcome to StudyMite!");  
};  

7. What is an anonymous function?

An anonymous function is a function that is declared without an identifier (name). It is created dynamically at runtime using a function expression.

Because they lack a name, they are highly flexible and commonly used as callback functions, immediately invoked function expressions (IIFEs), or assigned directly to variables.


8. Can an anonymous function be assigned to a variable?

Yes. This pattern is known as a function expression. Once assigned, the variable can be used to invoke the function just like a named function.

const greet = function() {
  return "Hello!";
};

console.log(greet()); // Output: "Hello!"

9. What is a named function in JavaScript?

A named function is declared with a specific name identifier. Unlike anonymous function expressions, named function declarations are hoisted, meaning they can be called before they are defined in the code.

// Calling the function before its declaration works due to hoisting
sayHello(); 

function sayHello() {
  console.log("Hello!");
}

10. What is a closure in JavaScript?

A closure is the combination of a function bundled together with references to its surrounding state (the lexical environment). In other words, a closure gives an inner function access to the outer function's scope even after the outer function has finished executing.

function outerFunction(outerVariable) {
  return function innerFunction(innerVariable) {
    console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
  };
}

const newFunction = outerFunction("outside");
newFunction("inside"); // Output: Outer: outside, Inner: inside

11. Which method is used to return the character at a specific index?

The charAt() method returns the character at a specified index in a string.

  • The index starts at 0 and goes up to length - 1.
  • If the index is out of range, it returns an empty string "".
const str = "StudyMite";
console.log(str.charAt(0)); // Output: "S"
console.log(str.charAt(5)); // Output: "M"

12. What is the difference between JavaScript and JScript?

  • JavaScript is the original scripting language developed by Netscape.
  • JScript was Microsoft's reverse-engineered implementation of JavaScript, created for Internet Explorer to avoid trademark issues.
  • Today, both have been standardized under ECMAScript, making the historical distinction obsolete in modern development.

13. How do you write a "Hello World" script in JavaScript?

You can output "Hello World" in several ways depending on your environment:

<!-- Writing directly to the HTML document -->
<script type="text/javascript">  
  document.write("StudyMite says Hello World!");  
</script>  

<!-- Printing to the developer console (Recommended for debugging) -->
<script type="text/javascript">  
  console.log("Hello World!");  
</script>  

To link an external JavaScript file, use the <script> tag with the src attribute pointing to the file path. This is typically placed inside the <head> or just before the closing </body> tag.

<script type="text/javascript" src="studymite.js"></script>

15. Is JavaScript case-sensitive?

Yes, JavaScript is strictly case-sensitive. Variables, function names, and keywords must be written consistently.

let studyMite = "Platform A";
let Studymite = "Platform B";

// These are treated as two completely different variables
console.log(studyMite); // Platform A
console.log(Studymite);  // Platform B

16. What is the Browser Object Model (BOM)?

The Browser Object Model (BOM) allows JavaScript to interact with the browser window. The default, top-level object of the BOM is the window object.

Key properties of the BOM include:

  • window.history
  • window.navigator
  • window.screen
  • window.location
  • window.document

17. What is the Document Object Model (DOM)?

The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of an HTML or XML document as a tree of objects. JavaScript uses the DOM to dynamically access, add, change, or delete HTML elements and styles.


18. What is the purpose of the window object?

The window object represents the browser window containing a DOM document. It is automatically created by the browser and acts as the global execution context for client-side JavaScript. Any global variable or function automatically becomes a property of the window object.


19. What is the purpose of the history object?

The history object is a property of the window object and contains the browser's session history (the pages visited in the current tab).

Commonly used methods include:

  • history.back(): Loads the previous URL in the history list.
  • history.forward(): Loads the next URL in the history list.
  • history.go(number): Loads a specific page from the session history based on a relative limit (e.g., -1 for back, 1 for forward).

20. How do you write comments in JavaScript?

JavaScript supports both single-line and multi-line comments:

// This is a single-line comment

/* 
   This is a 
   multi-line comment 
*/

21. How do you declare a function in JavaScript?

To declare a function, use the function keyword followed by the function name, parameters in parentheses, and the code block in curly braces:

function greetUser(name) {  
  return `Hello, ${name}!`;  
}  

22. What are the data types in JavaScript?

JavaScript data types are divided into two main categories:

Primitive Data Types

Stored directly in the location that the variable accesses. They are immutable.

  • String: Textual data (e.g., "Hello")
  • Number: Double-precision 64-bit binary format IEEE 754 values (e.g., 42, 3.14)
  • BigInt: For integers larger than the safe Number limit
  • Boolean: true or false
  • Undefined: A variable that has been declared but not assigned a value
  • Null: Represents the intentional absence of any object value
  • Symbol: A unique and immutable identifier

Non-Primitive (Reference) Data Types

Stored as references in memory.

  • Object: Collections of key-value pairs (including Arrays and Functions)

23. What is the difference between == and ===?

  • == (Loose Equality): Compares two values for equality after performing type coercion (converting the data types if they are different).
  • === (Strict Equality): Compares both the value and the data type without coercion. If the types are different, it immediately returns false.
console.log(5 == "5");  // true (string "5" is coerced to number 5)
console.log(5 === "5"); // false (different types: number vs string)

24. How do you write HTML code dynamically using JavaScript?

You can dynamically insert HTML into a webpage using the innerHTML property of a DOM element:

document.getElementById('studymite').innerHTML = "<h2>This is a dynamic heading</h2>";   

25. How do you write plain text dynamically using JavaScript?

To insert plain text without parsing it as HTML, use the innerText or textContent properties. This is safer than innerHTML because it prevents Cross-Site Scripting (XSS) attacks.

document.getElementById('studymite').innerText = "This is safe, plain text.";

26. How do you create objects in JavaScript?

There are three common ways to create an object:

1. Object Literal

const student = { name: "Alex", age: 21 };

2. Using the new Object() syntax

const student = new Object();
student.name = "Alex";
student.age = 21;

3. Using a Constructor Function

function Student(name, age) {
  this.name = name;
  this.age = age;
}
const student1 = new Student("Alex", 21);

27. How do you create an array in JavaScript?

You can create arrays using three different approaches:

const colors = ["red", "green", "blue"];

2. Creating an instance of Array

const colors = new Array();
colors[0] = "red";
colors[1] = "green";

3. Using the Array Constructor

const colors = new Array("red", "green", "blue");

28. What is the isNaN() function?

The isNaN() function determines whether a value is NaN (Not-a-Number). It returns true if the value is not a valid number (or cannot be coerced into one), and false if it is a valid number.

console.log(isNaN("Hello")); // true (cannot be converted to a number)
console.log(isNaN(123));     // false (is a valid number)
console.log(isNaN("123"));   // false (can be coerced to the number 123)

29. What is the output of 10 + 20 + "30" in JavaScript?

The output is "3030".

Explanation:

  1. JavaScript evaluates the expression from left to right.
  2. First, 10 + 20 is evaluated. Since both are numbers, they are added arithmetically to get 30.
  3. Next, 30 + "30" is evaluated. Since one operand is a string, JavaScript coerces the number 30 into a string and performs concatenation, resulting in "3030".

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

The output is "102030".

Explanation:

  1. Evaluation starts from left to right.
  2. First, "10" + 20 is evaluated. Because "10" is a string, the number 20 is coerced to a string, resulting in "1020".
  3. Next, "1020" + 30 is evaluated. Again, string concatenation occurs, resulting in "102030".

31. What is the difference between client-side and server-side JavaScript?

  • Client-Side JavaScript: Runs directly inside the user's web browser. It has access to the DOM and BOM but cannot access the server's file system or database directly.
  • Server-Side JavaScript: Runs on a server (e.g., via Node.js). It has access to server resources, file systems, databases, and network ports, but does not have access to browser-specific objects like window or document.

32. Where are cookies stored on the hard disk?

Cookies are stored on the user's hard drive by the web browser. The exact storage path depends on the operating system and the browser:

  • Google Chrome (Windows): Typically stored in an SQLite database at %localappdata%\Google\Chrome\User Data\Default\Network\Cookies.
  • Firefox (Windows): Stored in a cookies.sqlite file inside the user's profile folder.

33. What is the purpose of the Map object?

A Map is a collection of keyed data items, similar to an Object. However, there are key differences:

  • A Map allows keys of any type (including functions, objects, and primitives).
  • It maintains the insertion order of its elements.
  • It has a built-in size property for easy length retrieval.
const map = new Map();
map.set('name', 'StudyMite');
map.set(1, 'One');

console.log(map.get('name')); // StudyMite
console.log(map.size);        // 2

34. What is the difference between undefined and null?

  • undefined: Means a variable has been declared but has not yet been assigned a value. It is the default value of uninitialized variables.
  • null: An assignment value that represents the intentional absence of any object value. It must be explicitly assigned.
let a; 
console.log(a); // undefined

let b = null;
console.log(b); // null

35. How do you set the cursor to a "wait" state using JavaScript?

You can change the cursor style dynamically by modifying the CSS cursor property of the document.body:

// Sets the cursor to the loading spinner/hourglass
document.body.style.cursor = "wait";   

36. How do you create a three-dimensional array in JavaScript?

A three-dimensional array is created by nesting arrays within arrays:

// Creating a 3D array
const array3D = [
  [
    [1, 2], [3, 4]
  ],
  [
    [5, 6], [7, 8]
  ]
];

console.log(array3D[0][1][0]); // Output: 3

37. What is the purpose of the Math object?

The built-in Math object provides properties and methods for mathematical constants and functions. Unlike other global objects, Math is not a constructor; all properties and methods are static.

console.log(Math.PI);       // 3.141592653589793
console.log(Math.sqrt(16));  // 4
console.log(Math.random());  // Random number between 0 and 1

38. What is negative infinity?

-Infinity is a special numeric value in JavaScript that is smaller than any other number. It is returned when a negative number is divided by zero, or when a value overflows the lower limit of JavaScript's numeric range.

const result = -5 / 0;
console.log(result); // Output: -Infinity

39. What is the difference between View State and Session State?

While these terms are primarily associated with server-side frameworks (like ASP.NET), they represent fundamental web state concepts:

  • View State: Maintains state data specific to a single page or component across postbacks. It is client-side.
  • Session State: Maintains user-specific data on the server side across multiple pages/requests during a user's active session.

40. What pop-up boxes are available in JavaScript?

JavaScript offers three standard dialog boxes:

  • Alert Box: Displays a message with an "OK" button. Used to show warnings or info.
    alert("This is an alert!");
    
  • Confirm Box: Displays a message with "OK" and "Cancel" buttons. Returns true or false.
    const userAgreed = confirm("Do you want to proceed?");
    
  • Prompt Box: Displays an input field for user text. Returns the entered string or null.
    const name = prompt("Please enter your name:");
    

41. How do you detect the user's Operating System using JavaScript?

You can retrieve operating system details using the navigator.appVersion or the modern navigator.userAgentData properties.

console.log(navigator.appVersion); 

42. How do you submit an HTML form using JavaScript?

You can trigger a form submission programmatically by calling the .submit() method on the form element:

<form name="myform" action="submit.php">  
  Search: <input type="text" name="query" />  
  <a href="javascript:submitForm()">Submit Search</a>  
</form>  

<script type="text/javascript">  
  function submitForm() {  
    document.myform.submit();  
  }  
</script>  

43. Which is faster: JavaScript or ASP?

JavaScript (client-side) is generally faster for user-facing interactions because it runs locally inside the user's browser. It does not require a network roundtrip to a web server to execute simple logic, unlike server-side scripts like ASP.


44. How are exceptions handled in JavaScript?

Exceptions are handled using try...catch...finally blocks. You can also manually throw custom errors using the throw statement.

try {
  // Code that might throw an error
  let result = riskyOperation();
} catch (error) {
  // Code to handle the error
  console.error("An error occurred: " + error.message);
} finally {
  // Code that always executes regardless of an error
  console.log("Cleanup complete.");
}

45. How do you validate a form in JavaScript?

You can intercept form submission to check input values before sending them to the server:

<script>  
function validateForm() {  
  const name = document.myform.name.value;  
  const password = document.myform.password.value;  
    
  if (name === "" || name === null) {  
    alert("Name cannot be blank.");  
    return false;  
  } else if (password.length < 6) {  
    alert("Password must be at least 6 characters long.");  
    return false;  
  }
  return true;
}  
</script>  

<form name="myform" method="post" action="register.php" onsubmit="return validateForm()">  
  Name: <input type="text" name="name"><br/>  
  Password: <input type="password" name="password"><br/>  
  <input type="submit" value="Register">  
</form>  

46. How do you validate data patterns in JavaScript?

Data validation patterns (like emails, phone numbers, or zip codes) are best validated using Regular Expressions (Regex).

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const email = "test@studymite.com";

if (emailRegex.test(email)) {
  console.log("Valid Email");
} else {
  console.log("Invalid Email");
}

47. What is the this keyword in JavaScript?

The this keyword refers to the object that is currently executing or "owning" the function. Its value is determined by how the function is called (execution context):

  • In a method, this refers to the owner object.
  • Alone or in a regular function, this refers to the global object (or undefined in strict mode).
  • In an event handler, this refers to the element that received the event.

48. Why is debugging required in JavaScript?

Debugging is the systematic process of identifying, isolating, and fixing bugs or unintended behaviors within your code. In JavaScript, you can debug using:

  • console.log() to print values to the console.
  • The browser's built-in Developer Tools (F12) to inspect elements, monitor network requests, and analyze execution.
  • The debugger keyword.

49. What is the debugger keyword?

The debugger keyword acts as a code-level breakpoint. If the browser's developer tools are open when the script runs, execution will pause automatically at the debugger statement, allowing you to step through variables and inspect the call stack.

function calculateTotal(price, tax) {
  let total = price + tax;
  debugger; // Execution pauses here if DevTools are open
  return total;
}

Finished reading?

Was this helpful?

Your feedback shapes better tutorials for everyone.