JavaScript Intermediate Interview Questions and Answers
JavaScript is a dynamic and versatile language that forms the backbone of web development. For developers at an intermediate level, mastering concepts beyond the basics is crucial for building scalable and efficient applications. In this section, we’ll discuss important JavaScript interview questions aimed at candidates with 3-5 years of experience. These questions will cover important topics such as loops, closures, file handling, and error management in JavaScript.
21. What are the looping structures in JavaScript?
JavaScript provides multiple ways to implement loops:
while
loop: Repeats code as long as a specified condition is true.javascriptCopy codelet i = 0; while (i < 5) { console.log(i); i++; }
for
loop: Combines initialization, condition, and increment/decrement in one line.javascriptCopy codefor (let i = 0; i < 5; i++) { console.log(i); }
do-while
loop: Similar to thewhile
loop, but checks the condition after the first iteration.javascriptCopy codelet i = 0; do { console.log(i); i++; } while (i < 5);
22. How can the style/class of an element be changed?
You can change an element’s style or class dynamically by using document.getElementById()
or other DOM methods.
document.getElementById("myElement").style.color = "red"; // Change style
document.getElementById("myElement").className = "newClass"; // Change class
23. Explain how to read and write a file using JavaScript?
In Node.js, you can read and write files using the fs
(File System) module:
- Reading a file:javascriptCopy code
const fs = require('fs'); fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });
- Writing to a file:javascriptCopy code
const fs = require('fs'); fs.writeFile('example.txt', 'Hello, World!', (err) => { if (err) throw err; console.log('File written successfully'); });
24. What is Variable Typing in JavaScript?
Variable typing refers to JavaScript’s ability to change the type of a variable dynamically. A variable can be assigned different data types during its lifetime.
let variable = 42; // Initially a number
variable = "Hello"; // Now it's a string
25. How to convert a string of any base to an integer in JavaScript?
The parseInt()
function is used to convert a string to an integer, where the second argument specifies the base (radix).
console.log(parseInt("10", 2)); // Outputs 2 (binary to decimal)
console.log(parseInt("10", 8)); // Outputs 8 (octal to decimal)
26. How to detect the operating system on the client machine?
You can detect the operating system of the client using navigator.appVersion
or navigator.userAgent
properties.
console.log(navigator.appVersion);
console.log(navigator.userAgent);
27. What are the types of pop-up boxes available in JavaScript?
JavaScript provides three types of pop-up boxes:
- Alert Box: Displays a message with an OK button.
- Confirm Box: Displays a message with OK and Cancel buttons.
- Prompt Box: Displays a dialog box that prompts the user to input text.
alert("This is an alert box!");
confirm("Are you sure?");
prompt("Please enter your name:");
28. What is the difference between an alert box and a confirmation box?
- Alert Box: Displays a message with only one button, typically used to notify the user.
- Confirmation Box: Displays a message with two buttons, OK and Cancel, allowing the user to make a choice.
alert("This is an alert!"); // OK only
confirm("Are you sure?"); // OK and Cancel
29. What are the disadvantages of using innerHTML
in JavaScript?
Disadvantages of using innerHTML
include:
- Replaces Existing Content: Modifying
innerHTML
will replace the entire content, including any event listeners attached to the elements. - Performance: Changing
innerHTML
can lead to performance issues, especially when updating large sections of the DOM.
document.getElementById('myDiv').innerHTML += 'New Content';
30. What is the use of void(0)
?
The void(0)
is often used in hyperlinks to prevent the page from refreshing or navigating to another page. It allows you to call a JavaScript function without any page load.
<a href="javascript:void(0);" onclick="myFunction()">Click Here</a>
31. What is ‘Strict Mode’ in JavaScript and how can it be enabled?
Strict mode is a feature introduced in ECMAScript 5 that makes JavaScript more secure by throwing errors for certain actions like using undeclared variables. It can be enabled by adding "use strict"
at the beginning of a script or function.
"use strict";
x = 3.14; // This will throw an error because 'x' is undeclared
32. How to get the status of a checkbox in JavaScript?
The checked
property of a checkbox input element can be used to check if it’s selected.
let isChecked = document.getElementById('myCheckbox').checked;
33. What are closures in JavaScript and when should they be used?
A closure is created when a function retains access to variables from its outer scope even after the outer function has executed. Closures are useful for data encapsulation and creating private variables.
function outerFunction() {
let count = 0;
return function innerFunction() {
count++;
return count;
};
}
let counter = outerFunction();
console.log(counter()); // 1
console.log(counter()); // 2
34. What is the difference between call()
and apply()
methods in JavaScript?
call()
: Invokes a function and allows you to pass arguments individually.apply()
: Invokes a function but accepts an array of arguments.
function greet(greeting, name) {
console.log(greeting + ", " + name);
}
greet.call(null, "Hello", "Alice");
greet.apply(null, ["Hello", "Bob"]);
35. How can you target a particular frame from a hyperlink in JavaScript?
The target
attribute in a hyperlink allows you to specify the frame to load the linked document.
<a href="example.html" target="newframe">Open in New Frame</a>
36. What are the different types of errors in JavaScript?
JavaScript errors are categorized into:
- Syntax Errors: Mistakes in the code syntax.
- Runtime Errors: Errors that occur during the execution of the program.
- Logical Errors: Errors in the logic of the code that result in incorrect output.
37. What is the difference between JavaScript and JScript?
- JavaScript: A scripting language developed by Netscape for creating interactive web pages.
- JScript: Microsoft’s implementation of JavaScript, often used in Internet Explorer.
38. What does var myArray = [[]];
declare?
This declares a two-dimensional array in JavaScript. myArray[0]
is an empty array.
39. How can HTML elements be accessed in JavaScript?
HTML elements can be accessed using:
getElementById()
getElementsByClassName()
getElementsByTagName()
querySelector()
40. What is the difference between innerHTML
and innerText
?
innerHTML
: Retrieves or sets the HTML content of an element.innerText
: Retrieves or sets the text content of an element, ignoring HTML tags.
document.getElementById('myDiv').innerHTML = "<strong>Bold Text</strong>"; // Renders as bold text
document.getElementById('myDiv').innerText = "<strong>Bold Text</strong>"; // Displays as plain text
41. What is event bubbling in JavaScript?
Event bubbling is the process where an event starts from the innermost target element and propagates to outer elements in the DOM hierarchy. It allows an event handler attached to a parent element to also handle events triggered by its children.
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked");
});
document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked");
});
These intermediate JavaScript questions cover key areas like closures, error handling, and DOM manipulation, preparing you for real-world coding challenges and helping you stand out in technical interviews.