In this article, you will explore intermediate-level JavaScript interview questions and answers that are commonly asked in technical interviews. Before diving in, it’s recommended to review a complete JavaScript Tutorial and JavaScript Interview Questions and Answers – Beginner Level to build a strong foundation.
1. What are all the looping structures in JavaScript?
JavaScript provides several looping structures to execute a block of code repeatedly based on a condition. The main looping structures are:
- while loop: This loop executes a block of code as long as a specified condition evaluates to
true
. It checks the condition before executing the code, making it an entry-controlled loop. If the condition is false initially, the loop body may never execute.
let i = 0;
while (i < 5) {
console.log(i); // Outputs: 0, 1, 2, 3, 4
i++;
}
- for loop: The
for
loop is a concise way to iterate, combining initialization, condition, and increment/decrement in a single line. It’s ideal for scenarios where the number of iterations is known.
for (let i = 0; i < 5; i++) {
console.log(i); // Outputs: 0, 1, 2, 3, 4
}
- do-while loop: Similar to the
while
loop, but it checks the condition after executing the code block, ensuring the loop body runs at least once. It’s an exit-controlled loop.
let i = 0;
do {
console.log(i); // Outputs: 0, 1, 2, 3, 4
i++;
} while (i < 5);
Additionally, JavaScript supports for...in (for iterating over object properties) and for...of (for iterating over iterable objects like arrays) loops, though they are specialized for specific use cases.
2. How can the style/class of an element be changed?
To modify the style or class of an HTML element in JavaScript, you can use the document.getElementById()
method to select the element and then update its style
or className
properties.
- Changing Style: The
style
property allows you to directly modify inline CSS properties of an element. For example:document.getElementById("myText").style.fontSize = "16px";
document.getElementById("myText").style.color = "blue";
This approach applies inline styles, which override external CSS unless !important
is used. - Changing Class: The
className
property replaces the entire class attribute of an element with a new class.document.getElementById("myText").className = "newClass";
To add or remove classes without overwriting existing ones, use the classList
API:document.getElementById("myText").classList.add("newClass");
document.getElementById("myText").classList.remove("oldClass");
document.getElementById("myText").classList.toggle("active");
Using classList
is preferred for class manipulation as it’s safer and more flexible.
3. Explain how to read and write a file using JavaScript?
In JavaScript, file operations depend on the environment (browser or Node.js). In Node.js, the fs
(File System) module is used for reading and writing files.
- Reading a File: The
fs.readFile()
function reads the contents of a file asynchronously. It takes three arguments: the file path, optional encoding (e.g., 'utf8'
), and a callback function to handle the result.const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File contents:', data);
});
- Writing a File: The
fs.writeFile()
function writes data to a file, overwriting it if it exists. It takes the file path, data to write, and a callback function.const fs = require('fs');
fs.writeFile('example.txt', 'Hello, World!', (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('File written successfully');
});
In the browser, file operations are limited for security reasons. You can use the File API to read files selected by the user via an <input type="file">
element, but writing files requires user interaction (e.g., triggering a download).
4. What is called variable typing in JavaScript?
Variable typing in JavaScript refers to the dynamic and loosely-typed nature of variables, where a variable’s type is determined at runtime and can change during execution. A single variable can hold different types of values (e.g., number, string) without explicit type declarations, as explained in JavaScript Data Types.
For example:
let geeks = 42; // geeks is a number
console.log(typeof geeks); // Outputs: "number"
geeks = "GeeksforGeeks"; // geeks is now a string
console.log(typeof geeks); // Outputs: "string"
This flexibility is due to JavaScript’s dynamic typing, but it can lead to errors if type changes are not managed carefully. Use typeof
or strict equality (===
) to handle type checks.
5. How to convert the string of any base to an integer in JavaScript?
The parseInt()
function converts a string to an integer in a specified base (radix). It takes two arguments: the string to parse and the base (2 to 36).
For example:
console.log(parseInt("1010", 2)); // Outputs: 10 (binary to decimal)
console.log(parseInt("FF", 16)); // Outputs: 255 (hexadecimal to decimal)
console.log(parseInt("123", 10)); // Outputs: 123 (decimal)
If the string is invalid or doesn’t match the base, parseInt()
returns NaN
:
console.log(parseInt("hello", 10)); // Outputs: NaN
Always specify the radix to avoid inconsistent behavior across browsers, especially for strings like "08"
(which older browsers might interpret as octal).
6. Explain how to detect the operating system on the client machine?
To detect the operating system in a browser, use the navigator
object’s appVersion
or userAgent
properties, which return strings containing browser and OS details. The userAgent
is more commonly used but requires parsing to extract the OS.
For example:
const userAgent = navigator.userAgent;
let os = "Unknown";
if (userAgent.includes("Win")) os = "Windows";
else if (userAgent.includes("Mac")) os = "MacOS";
else if (userAgent.includes("Linux")) os = "Linux";
else if (userAgent.includes("Android")) os = "Android";
else if (userAgent.includes("iOS")) os = "iOS";
console.log("Operating System:", os);
Note that userAgent
can be spoofed, so it’s not foolproof. For more reliable detection, consider libraries like platform.js
. In Node.js, use process.platform
(e.g., 'win32'
, 'darwin'
, 'linux'
).
JavaScript provides three types of pop-up boxes for user interaction, as described in JavaScript Popup Boxes:
- Alert: Displays a simple message with an OK button to acknowledge it.
alert("This is an alert box!");
- Confirm: Displays a message with OK and Cancel buttons, returning
true
(OK) or false
(Cancel).if (confirm("Do you want to proceed?")) {
console.log("User clicked OK");
} else {
console.log("User clicked Cancel");
}
- Prompt: Displays a message with a text input field, OK, and Cancel buttons. Returns the user’s input as a string or
null
if canceled.let name = prompt("Enter your name:", "Guest");
console.log(name || "No input provided");
These are synchronous and block the UI, so modern applications often use custom modals for better UX.
8. What is the difference between an alert box and a confirmation box?
The key difference is that alert
is for notifications, while confirm
is for decision-making.
9. What is the disadvantage of using innerHTML in JavaScript?
Using innerHTML
to manipulate the DOM has several disadvantages:
- Security Risks: Setting
innerHTML
with user input can lead to Cross-Site Scripting (XSS) attacks if the input isn’t sanitized. Malicious scripts can be injected and executed.// Unsafe usage
document.getElementById("myDiv").innerHTML = userInput; // Risky if userInput contains <script>alert('XSS');</script>
- Performance: Replacing
innerHTML
re-parses and re-renders the entire DOM subtree, which can be slower than using specific DOM methods like appendChild()
or textContent
for simple updates. - Event Handlers: Setting
innerHTML
overwrites existing event handlers attached to elements unless they’re managed externally (e.g., via event delegation).document.getElementById("myDiv").innerHTML = "<p>New content</p>"; // Removes existing event listeners
- Unintended Overwrites: Using
innerHTML +=
to append content re-parses the existing content, causing performance issues and potentially breaking dynamic behavior.document.getElementById("myDiv").innerHTML += "<p>More</p>"; // Inefficient re-parsing
For safer alternatives, use textContent
for plain text or DOM methods like createElement()
, appendChild()
for structured content.
10. What is the use of void(0)?
The void(0)
expression evaluates to undefined
and is often used in href
attributes to prevent the browser from navigating to a new page when a link is clicked. It’s commonly seen in JavaScript-driven links that trigger functions instead of loading a new URL.
For example:
<a href="javascript:void(0);" onclick="myFunction()">Click me</a>
<script>
function myFunction() {
alert("Function triggered!");
}
</script>
Here, void(0)
ensures the link navigation doesn’t occur. However, modern practices favor:
- Using
event.preventDefault()
in event handlers:<a href="#" onclick="event.preventDefault(); myFunction()">Click me</a>
- Or using
addEventListener
:document.querySelector("a").addEventListener("click", (e) => {
e.preventDefault();
myFunction();
});
void(0)
is still used but is considered less readable and outdated compared to modern event handling.
11. What are JavaScript Cookies?
Cookies are small key-value pairs stored on a user’s browser by a website. They are used to store user-specific data, such as preferences, authentication tokens, or tracking information. Cookies are sent with HTTP requests to the server, allowing websites to maintain state across sessions.
Key points:
- Purpose: Store data like language preferences, shopping cart items, or session IDs.
- Size Limit: Typically ~4KB per cookie.
- Expiration: Cookies can be set to expire at a specific date or persist until the browser is cleared.
- Access: Accessible by the server (via HTTP headers) and client (via
document.cookie
).
Example use case: Remembering a user’s theme preference (e.g., dark/light mode).
12. How to create a cookie using JavaScript?
To create a cookie, assign a string to document.cookie
with the format name=value; expires=date; path=/
. For example:
function setCookie(name, value, days) {
let expires = "";
if (days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
setCookie("username", "JohnDoe", 7); // Sets cookie for 7 days
The expires
attribute sets the cookie’s lifespan, and path=/
makes it accessible across the site.
13. How to read a cookie using JavaScript?
To read cookies, access document.cookie
, which returns a semicolon-separated string of all cookies. Parse the string to extract specific cookies.
For example:
function getCookie(name) {
let nameEQ = name + "=";
let cookies = document.cookie.split(';');
for (let cookie of cookies) {
cookie = cookie.trim();
if (cookie.startsWith(nameEQ)) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
console.log(getCookie("username")); // Outputs: "JohnDoe" if exists
Libraries like js-cookie
simplify cookie management for complex scenarios.
14. How to delete a cookie using JavaScript?
To delete a cookie, set its expires
date to a past time, effectively marking it for removal. Ensure the same path
and domain
are used as when the cookie was created.
For example:
function deleteCookie(name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/";
}
deleteCookie("username");
Setting max-age=0
is another alternative to expire the cookie immediately. Verify the path matches to avoid issues with undeleted cookies, as explained in JavaScript Cookies.
15. What are escape characters and escape() function?
Common escape sequences include:
Use encodeURIComponent()
or encodeURI()
for modern URL encoding needs.
16. Whether JavaScript has concept-level scope?
JavaScript does not have concept-level scope (also known as block-level scope) in traditional ES5 code, but it was introduced in ES6 via let
and const
. In older JavaScript (using var
):
- Variables declared inside a function have function scope, meaning they’re accessible throughout the function, regardless of blocks (e.g., curly braces
{}
). - Variables declared outside functions have global scope.
For example:
function example() {
var x = 10;
if (true) {
var x = 20; // Same x, overwrites
}
console.log(x); // Outputs: 20
}
example();
In ES6, let
and const
provide block-level scope, limiting variables to their block:
function example() {
let x = 10;
if (true) {
let x = 20; // Different x
}
console.log(x); // Outputs: 10
}
example();
Modern JavaScript favors let
and const
for better scoping and to avoid var
pitfalls.
17. How can generic objects be created in JavaScript?
Generic objects can be created in several ways:
- Object Constructor:
let obj = new Object();
obj.name = "John";
obj.age = 25;
- Object Literal (preferred):
let obj = {
name: "John",
age: 25
};
- Object.create:
let obj = Object.create(null); // No prototype
obj.name = "John";
obj.age = 25;
Object literals are the most concise and commonly used method. Object.create
is useful for custom prototyping.
18. Which keywords are used to handle exceptions?
JavaScript uses exception handling to manage runtime errors with the following keywords:
try
: Wraps code that might throw an error.catch
: Handles the error if one occurs.finally
: Executes code after try
/catch
, regardless of the outcome.throw
: Creates custom errors.
For example:
try {
let result = riskyFunction();
console.log(result);
} catch (error) {
console.error("Error:", error.message);
} finally {
console.log("Cleanup done");
}
function riskyFunction() {
throw new Error("Something went wrong");
}
This structure ensures graceful error handling and cleanup.
19. What is the use of the blur function?
The blur()
method removes focus from an element, triggering a blur
event. It’s useful for programmatically shifting focus or validating input fields.
For example:
document.getElementById("myInput").focus();
setTimeout(() => {
document.getElementById("myInput").blur(); // Removes focus after 2s
}, 2000);
You can also listen for blur events:
document.getElementById("myInput").addEventListener("blur", () => {
console.log("Input lost focus");
});
Use blur()
for form validation or UI interactions.
20. What is the unshift method in JavaScript?
The unshift()
method adds one or more elements to the beginning of an array and returns the new array length. It modifies the original array.
For example:
let array = [2, 3, 4];
array.unshift(0, 1); // Adds 0 and 1
console.log(array); // Output: [0, 1, 2, 3, 4]
console.log(array.length); // Output: 5
Unlike push()
(adds to the end), unshift()
shifts existing elements to higher indices. It’s less performant for large arrays due to this shifting.
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics
My Profile