JavaScript Interview Questions and Answers: Basic to Advanced
Candidates preparing for JavaScript interviews should understand variables, data types, operators, conditional statements, loops, functions, arrays, objects, and scope. They should also learn ES6+ features, closures, hoisting, promises, asynchronous programming, the event loop, DOM manipulation, event handling, and JavaScript classes. For practical preparation, candidates should practise coding problems involving strings, arrays, objects, number manipulation, and commonly used JavaScript methods.
Introduction
JavaScript is one of the most important programming languages for modern web development. It enables developers to create interactive websites, dynamic user interfaces, browser-based applications, and server-side applications using environments such as Node.js.
For aspiring frontend developers, JavaScript provides the foundation for working with HTML, CSS, browser events, APIs, and modern frontend frameworks. Its flexibility also makes it useful for backend development, automation, and full-stack application development.
However, preparing for a JavaScript technical interview involves more than learning basic syntax. Interviewers frequently evaluate whether candidates understand how JavaScript handles variables, functions, objects, asynchronous operations, memory references, and browser interactions.
Fresh graduates may initially find concepts such as closures, hoisting, promises, and the event loop challenging. Understanding these topics through practical examples makes it easier to explain program behaviour and solve technical problems.
This guide covers JavaScript interview questions and answers from basic to advanced levels. It includes important programming concepts, practical code examples, output-based questions, browser-related topics, and coding exercises to help freshers prepare for entry-level developer interviews.
1. Basic JavaScript Interview Questions and Answers
1. What is JavaScript?
JavaScript is a high-level programming language primarily used to create interactive and dynamic web applications. It is supported by modern web browsers and can also run outside browsers through environments such as Node.js.
JavaScript allows developers to validate forms, respond to user interactions, update webpage content, communicate with APIs, and build complete applications.
Its major applications include:
- Frontend development: Creating interactive website interfaces and dynamic web pages.
- Backend development: Building server-side applications using Node.js.
- Web application development: Developing interactive applications that communicate with databases and APIs.
- Mobile development: Building mobile applications using JavaScript-based development frameworks.
- Automation: Creating scripts that automate repetitive development and browser-related tasks.
2. What are the main features of JavaScript?
JavaScript provides several features that make it useful for modern application development.
- Dynamic typing: Variables can refer to values of different types during program execution.
- Event-driven programming: Applications can respond to user actions such as clicks, keyboard input, and form submissions.
- First-class functions: Functions can be assigned to variables, passed as arguments, and returned from other functions.
- Object-oriented capabilities: JavaScript supports objects, prototypes, classes, inheritance, and encapsulation patterns.
- Asynchronous programming: Promises and async/await allow developers to manage operations that complete later.
- Cross-platform execution: JavaScript runs in modern browsers and several server-side and application environments.
- Extensive ecosystem: Developers can use numerous libraries, packages, and frameworks for application development.
These features make JavaScript an essential technology for frontend and full-stack development.
3. Who developed JavaScript?
JavaScript was created by Brendan Eich in 1995 while working at Netscape. It was initially developed for adding interactivity to web pages and later became a major programming language for web application development.
JavaScript is standardised through ECMAScript, the language specification maintained by Ecma International.
4. What is the difference between JavaScript and Java?
Despite their similar names, JavaScript and Java are separate programming languages with different language designs and execution models.
| JavaScript | Java |
|---|---|
| Dynamically typed language. | Statically typed language. |
| Commonly used for frontend and backend web development. | Used for enterprise, backend, Android-related ecosystems, and other applications. |
| Supports prototype-based object inheritance and class syntax. | Primarily uses class-based object-oriented programming. |
| Commonly executes in browsers and JavaScript runtimes. | Commonly executes on the Java Virtual Machine. |
| Uses let, const, and var for variable declarations. | Uses explicit type declarations for variables. |
The two languages have different syntax rules, runtime environments, and programming characteristics.
5. How do you include JavaScript in an HTML document?
JavaScript can be added to an HTML document using the script element. Developers can write JavaScript directly inside the HTML file or link an external JavaScript file.
Internal JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script>
console.log("Hello, JavaScript!");
</script>
</body>
</html>
External JavaScript:
<script src="script.js" defer></script>
External files help separate application logic from HTML structure and make code easier to maintain. The defer attribute allows the browser to download the script without blocking HTML parsing and execute it after the document has been parsed.
6. What are variables in JavaScript?
Variables are named identifiers used to store and reference values during program execution.
JavaScript provides three commonly discussed variable declaration keywords: var, let, and const.
var name = "Arun";
let age = 22;
const course = "JavaScript";
console.log(name);
console.log(age);
console.log(course);
Variables allow developers to store information, process data, and reuse values throughout an application.
7. What is the difference between var, let, and const?
All three keywords declare variables, but they differ in scope, redeclaration rules, and reassignment behaviour.
| var | let | const |
|---|---|---|
| Function-scoped or globally scoped, depending on where declared. | Block-scoped. | Block-scoped. |
| Can be redeclared in the same scope. | Cannot be redeclared in the same scope. | Cannot be redeclared in the same scope. |
| Can be reassigned. | Can be reassigned. | Cannot be reassigned after initialization. |
| Can be accessed before its declaration through hoisting, with an initial value of undefined for its binding. | Has a temporal dead zone before declaration. | Has a temporal dead zone before declaration. |
Example:
var city = "Trichy";
let age = 22;
const country = "India";
age = 23;
console.log(city);
console.log(age);
console.log(country);
Developers generally prefer const when a binding does not need reassignment and let when reassignment is necessary. var is mainly encountered in older JavaScript code.
8. What are the different data types in JavaScript?
JavaScript has seven primitive data types and one non-primitive category commonly represented by objects.
| Data type | Example | Description |
|---|---|---|
| String | "Hello" | Represents text. |
| Number | 100, 25.5 | Represents integer and floating-point numbers. |
| Boolean | true | Represents logical values. |
| Undefined | undefined | Represents an unassigned or missing value. |
| Null | null | Represents an intentional absence of a value. |
| BigInt | 123n | Represents integers beyond the safe integer range of Number. |
| Symbol | Symbol("id") | Represents a unique symbol value. |
| Object | {name: "Arun"} | Represents collections and more complex data structures. |
Arrays, functions, dates, and many other JavaScript structures are objects.
9. What is the difference between null and undefined?
Both null and undefined represent the absence of a meaningful value, but they are used differently.
undefined commonly indicates that a variable has been declared but not assigned a value, or that a property does not exist.
null is generally assigned intentionally to indicate that a value is absent.
let name;
let address = null;
console.log(name);
console.log(address);
console.log(typeof null);
console.log(typeof undefined);
Output:
undefined
null
object
undefined
The result typeof null being "object" is a historical JavaScript behaviour and is not an indication that null is an object.
10. What is the difference between == and === in JavaScript?
The == operator performs loose equality comparison and may convert values to compatible types before comparing them. The === operator performs strict equality comparison without type coercion.
console.log(10 == "10");
console.log(10 === "10");
Output:
true
false
In the first comparison, JavaScript converts the string to a number. In the second comparison, the number and string have different types.
Using === is generally recommended because it makes comparisons more predictable.
11. What is type conversion in JavaScript?
Type conversion means changing a value from one data type to another.
JavaScript supports explicit conversion using functions such as Number(), String(), and Boolean(). It also performs implicit conversion in certain operations.
let number = "100";
let convertedNumber = Number(number);
console.log(convertedNumber + 50);
console.log(typeof convertedNumber);
Output:
150
number
Understanding type conversion is important because unexpected coercion can produce incorrect results in calculations and conditional expressions.
12. What is the difference between primitive and reference data types?
Primitive values include strings, numbers, booleans, null, undefined, BigInt, and symbols. Objects, including arrays and functions, are reference-type values in common JavaScript terminology.
Primitive values are immutable values. Objects are mutable, and variables holding objects refer to those objects.
let a = 10;
let b = a;
b = 20;
console.log(a);
console.log(b);
Output:
10
20
Changing b does not change the primitive value held by a.
Now consider an object:
let user1 = { name: "Arun" };
let user2 = user1;
user2.name = "Priya";
console.log(user1.name);
Output:
Priya
Both variables refer to the same object, so changing the object's property through one reference is visible through the other.
2. JavaScript Programming Interview Questions: Functions and Scope
13. What is a function in JavaScript?
A function is a reusable block of code designed to perform a specific operation. It can accept parameters, execute statements, and return a value.
function add(a, b) {
return a + b;
}
console.log(add(10, 20));
Output:
30
Functions improve code reuse, organisation, readability, and application maintenance.
14. What is the difference between function declaration and function expression?
A function declaration defines a named function using the function keyword. A function expression assigns a function to a variable.
// Function declaration
function greet() {
console.log("Hello");
}
// Function expression
const welcome = function() {
console.log("Welcome");
};
greet();
welcome();
Function declarations are hoisted with their function definitions, while a function expression assigned to a const or let variable cannot be accessed before the variable's initialization.
15. What is an arrow function in JavaScript?
An arrow function is a shorter way to write function expressions. It uses the => syntax and has lexical this behaviour.
const multiply = (a, b) => {
return a * b;
};
console.log(multiply(5, 4));
Output:
20
For a single expression, the return value can be written implicitly:
const square = number => number * number;
console.log(square(5));
Arrow functions are useful for callbacks and concise operations. They do not have their own this binding and cannot be used as constructors with new.
16. What are parameters and arguments in JavaScript?
Parameters are variables declared in a function definition, while arguments are the actual values passed when calling the function.
function greet(name) {
console.log("Hello " + name);
}
greet("Arun");
Here, name is the parameter and "Arun" is the argument.
17. What is the difference between local and global scope?
A global variable is accessible from the global scope and other scopes that can access it. A local variable is declared within a function or block and is limited by its scope rules.
let company = "Well Spring";
function display() {
let course = "JavaScript";
console.log(company);
console.log(course);
}
display();
The company variable is accessible inside the function, while course is local to the function.
Understanding scope helps prevent naming conflicts and unintended variable modifications.
18. What is hoisting in JavaScript?
Hoisting describes how JavaScript processes declarations before executing code within a scope.
Function declarations can generally be called before their position in the source code. Variables declared with var are hoisted and initialised with undefined, while let and const bindings remain in the temporal dead zone until their declarations are evaluated.
console.log(name);
var name = "Arun";
Output:
undefined
The following example produces a ReferenceError:
console.log(age);
let age = 22;
Understanding hoisting helps developers avoid unexpected errors related to variable access.
19. What is a closure in JavaScript?
A closure occurs when a function retains access to variables from its surrounding lexical scope, even after the outer function has finished executing.
function counter() {
let count = 0;
return function() {
count++;
return count;
};
}
const increment = counter();
console.log(increment());
console.log(increment());
console.log(increment());
Output:
1
2
3
The returned function remembers the count variable from its outer function. Closures are useful for creating private state, callbacks, and reusable function factories.
20. What is a callback function in JavaScript?
A callback is a function passed as an argument to another function so that it can be executed later or at a specific point in the operation.
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function welcome() {
console.log("Welcome to JavaScript");
}
greet("Arun", welcome);
Output:
Hello Arun
Welcome to JavaScript
Callbacks are commonly used in event handling, asynchronous operations, and array methods.
21. What is a higher-order function in JavaScript?
A higher-order function is a function that accepts another function as an argument, returns a function, or does both.
function calculate(a, b, operation) {
return operation(a, b);
}
const add = (x, y) => x + y;
console.log(calculate(10, 20, add));
Output:
30
Higher-order functions are widely used in functional programming and JavaScript methods such as map(), filter(), and reduce().
22. What is the difference between call(), apply(), and bind()?
These methods allow developers to control the value of this when working with regular functions.
| Method | Purpose |
|---|---|
| call() | Invokes a function immediately with a specified this value and individual arguments. |
| apply() | Invokes a function immediately with a specified this value and arguments supplied as an array-like object. |
| bind() | Returns a new function with a specified this value and optionally preset arguments. |
const person = {
name: "Arun"
};
function greet(city) {
console.log(this.name + " from " + city);
}
greet.call(person, "Trichy");
greet.apply(person, ["Chennai"]);
const boundGreet = greet.bind(person, "Madurai");
boundGreet();
Output:
Arun from Trichy
Arun from Chennai
Arun from Madurai
These methods are particularly useful when passing functions as callbacks or controlling function execution context.
3. JavaScript Arrays, Objects and ES6+ Interview Questions
23. What is an array in JavaScript?
An array is an ordered collection that stores multiple values in a single variable. Arrays can contain values of different data types and are indexed starting from zero.
const students = ["Arun", "Priya", "Kumar"];
console.log(students[0]);
Output:
Arun
Arrays are useful for storing collections of related information and processing them through loops and built-in methods.
24. What is the difference between map(), filter(), and reduce()?
These are important higher-order array methods used to process collections.
- map() creates a new array by transforming each element.
- filter() creates a new array containing elements that satisfy a condition.
- reduce() processes array elements and combines them into a single accumulated result.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const even = numbers.filter(n => n % 2 === 0);
const total = numbers.reduce((sum, n) => sum + n, 0);
console.log(doubled);
console.log(even);
console.log(total);
Output:
[2, 4, 6, 8, 10]
[2, 4]
15
These methods make collection processing more readable and reduce the need for repetitive loop logic.
25. What is the difference between push(), pop(), shift(), and unshift()?
These methods add or remove elements from JavaScript arrays.
| Method | Purpose |
|---|---|
| push() | Adds one or more elements to the end. |
| pop() | Removes and returns the last element. |
| shift() | Removes and returns the first element. |
| unshift() | Adds one or more elements to the beginning. |
const numbers = [10, 20, 30];
numbers.push(40);
numbers.pop();
numbers.shift();
numbers.unshift(5);
console.log(numbers);
Output:
[5, 20, 30]
Understanding these methods is useful when working with dynamic lists and application data.
26. What is an object in JavaScript?
An object is a collection of properties represented as key-value pairs. Each property can hold a value, function, or another object.
const student = {
name: "Arun",
age: 22,
course: "JavaScript",
display: function() {
console.log(this.name);
}
};
student.display();
Output:
Arun
Objects are used to represent structured information such as users, products, employees, and application settings.
27. What is destructuring in JavaScript?
Destructuring is an ES6 feature that allows developers to extract values from arrays or properties from objects and assign them to variables.
Array destructuring:
const numbers = [10, 20, 30];
const [a, b, c] = numbers;
console.log(a, b, c);
Object destructuring:
const student = {
name: "Arun",
age: 22
};
const { name, age } = student;
console.log(name, age);
Destructuring makes it easier to work with complex objects and arrays without repeatedly accessing individual properties.
28. What is the spread operator in JavaScript?
The spread operator (...) expands iterable elements or enumerable object properties into another array, object, or argument list.
const first = [10, 20];
const second = [30, 40];
const combined = [...first, ...second];
console.log(combined);
Output:
[10, 20, 30, 40]
It is commonly used to copy arrays, merge objects, and pass arguments to functions. Spread creates shallow copies, not deep copies.
29. What is the rest parameter in JavaScript?
The rest parameter (...) allows a function to accept multiple arguments and collect them into an array.
function sum(...numbers) {
return numbers.reduce((total, number) => total + number, 0);
}
console.log(sum(10, 20, 30, 40));
Output:
100
The rest parameter is useful when the number of function arguments is not fixed.
30. What are template literals in JavaScript?
Template literals are string literals enclosed in backticks. They allow variable interpolation and multiline strings.
const name = "Arun";
const course = "JavaScript";
const message = `Hello ${name}, welcome to ${course}!`;
console.log(message);
Output:
Hello Arun, welcome to JavaScript!
Template literals improve readability when creating dynamic messages and formatted strings.
31. What is optional chaining in JavaScript?
Optional chaining (?.) allows developers to access nested object properties or methods without causing an error when an intermediate value is null or undefined.
const user = {
name: "Arun",
address: {
city: "Trichy"
}
};
console.log(user.address?.city);
console.log(user.contact?.phone);
Output:
Trichy
undefined
Optional chaining is useful when working with API responses or objects whose properties may not always exist.
32. What is the difference between || and ?? in JavaScript?
Both operators provide fallback values, but they use different conditions.
The logical OR operator (||) returns the right-hand value when the left-hand value is falsy. The nullish coalescing operator (??) returns the right-hand value only when the left-hand value is null or undefined.
let age = 0;
console.log(age || 18);
console.log(age ?? 18);
Output:
18
0
The ?? operator is useful when zero, false, or an empty string are valid values that should not be replaced.
4. JavaScript Technical Interview Questions: DOM and Browser Concepts
33. What is the DOM in JavaScript?
DOM stands for Document Object Model. It represents an HTML document as a structured tree of objects that JavaScript can access and modify.
Using the DOM, developers can change webpage content, update styles, create elements, remove elements, and respond to user interactions.
For example:
document.getElementById("heading").textContent =
"Welcome to JavaScript";
This statement changes the text content of the HTML element with the ID heading.
34. What is the difference between getElementById() and querySelector()?
Both methods select elements from the DOM, but they work differently.
| getElementById() | querySelector() |
|---|---|
| Selects an element using its ID. | Selects the first element matching a CSS selector. |
| Accepts an ID string without the # prefix. | Supports CSS selector syntax. |
| Returns the matching element or null. | Returns the first matching element or null. |
const heading = document.getElementById("title");
const button = document.querySelector(".submit-btn");
querySelector() provides greater flexibility when selecting elements using classes, IDs, attributes, and other CSS selectors.
35. What is an event in JavaScript?
An event is an action or occurrence that JavaScript can detect and respond to.
Common browser events include:
- click when a user clicks an element.
- mouseover when a pointer moves over an element.
- keydown when a keyboard key is pressed.
- submit when a form is submitted.
- change when an input's value changes and the change is committed.
Events help developers create interactive webpages and responsive user interfaces.
36. What is event bubbling in JavaScript?
Event bubbling is the process in which an event triggered on an element propagates upward through its ancestor elements in the DOM.
For example, clicking a button inside a div can trigger click handlers on the button, its parent, and other ancestors when the event is configured to bubble.
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked");
});
document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked");
});
When the child is clicked, the child handler normally executes before the parent handler during bubbling.
37. What is event delegation in JavaScript?
Event delegation is a technique in which a single event listener is attached to a parent element to handle events from its child elements.
document.getElementById("list").addEventListener("click", (event) => {
if (event.target.matches("li")) {
console.log(event.target.textContent);
}
});
This approach is useful for handling dynamically added elements and reducing the number of individual event listeners.
38. What is the difference between preventDefault() and stopPropagation()?
Both methods are used when handling browser events, but they have different purposes.
preventDefault() prevents the browser's default action associated with an event, when that action is cancelable.
stopPropagation() prevents the event from continuing to propagate through the DOM.
For example, preventDefault() can stop a form from submitting through its normal browser behaviour, while stopPropagation() can prevent a click event from reaching ancestor event handlers.
These methods should be used carefully because they change normal browser interaction behaviour.
39. What is the difference between localStorage and sessionStorage?
Both are browser storage mechanisms that allow websites to store key-value data.
| localStorage | sessionStorage |
|---|---|
| Data generally persists until explicitly removed. | Data lasts for the lifetime of the page session. |
| Shared across tabs and windows of the same origin. | Associated with a particular browsing context and session. |
| Useful for persistent preferences. | Useful for temporary session-specific information. |
| Stores values as strings. | Stores values as strings. |
Example:
localStorage.setItem("username", "Arun");
const name = localStorage.getItem("username");
console.log(name);
Output:
Arun
Sensitive information such as authentication secrets should not be stored in browser storage without carefully considering security risks.
40. What is JSON in JavaScript?
JSON stands for JavaScript Object Notation. It is a lightweight text-based format used to exchange structured data between applications.
JavaScript provides two important methods for working with JSON.
- JSON.stringify() converts a JavaScript value into a JSON string.
- JSON.parse() converts a valid JSON string into a JavaScript value.
const student = {
name: "Arun",
age: 22
};
const jsonData = JSON.stringify(student);
const convertedData = JSON.parse(jsonData);
console.log(convertedData.name);
Output:
Arun
JSON is widely used when sending and receiving data through web APIs.
5. Advanced JavaScript Technical Interview Questions
41. What is synchronous and asynchronous programming in JavaScript?
Synchronous programming executes statements in sequence, where each operation normally completes before the next statement proceeds.
Asynchronous programming allows certain operations to be initiated without blocking the rest of the program while they wait for completion.
console.log("First");
setTimeout(() => {
console.log("Second");
}, 1000);
console.log("Third");
Output:
First
Third
Second
The timer callback runs later, allowing the remaining synchronous statements to execute first.
Asynchronous programming is particularly important when working with API requests, timers, file operations, and user interactions.
42. What is a Promise in JavaScript?
A Promise is an object that represents the eventual completion or failure of an asynchronous operation.
A Promise can be in one of three states:
- Pending: The operation has not completed.
- Fulfilled: The operation has completed successfully.
- Rejected: The operation has failed.
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Operation successful");
} else {
reject("Operation failed");
}
});
promise.then(result => {
console.log(result);
});
Output:
Operation successful
Promises help organise asynchronous code and provide methods such as then(), catch(), and finally().
43. What is async and await in JavaScript?
async and await are JavaScript features that simplify writing asynchronous code using a syntax similar to synchronous programming.
An async function always returns a Promise. The await keyword pauses the execution of the surrounding async function until the awaited Promise settles.
function getData() {
return Promise.resolve("Data received");
}
async function displayData() {
const result = await getData();
console.log(result);
}
displayData();
Output:
Data received
Using async and await can make asynchronous workflows easier to read and maintain.
44. What is the event loop in JavaScript?
The event loop is a mechanism that coordinates JavaScript execution, the call stack, and queued callbacks.
JavaScript execution commonly involves the following components:
- Call stack: Tracks functions currently being executed.
- Web APIs or runtime APIs: Handle operations such as timers, network requests, and browser events.
- Task queue: Holds callbacks waiting to be processed.
- Microtask queue: Holds Promise reaction jobs and other microtasks.
When the call stack becomes empty, the event loop processes queued work. Microtasks are generally processed before the next task begins.
Understanding the event loop helps developers explain why asynchronous operations execute in a particular order.
45. What is the difference between setTimeout() and setInterval()?
Both functions are used to schedule code execution.
| setTimeout() | setInterval() |
|---|---|
| Executes a callback once after a specified delay. | Schedules a callback to repeat at a specified interval. |
| Returns a timer identifier. | Returns a timer identifier. |
| Can be cancelled using clearTimeout(). | Can be cancelled using clearInterval(). |
setTimeout(() => {
console.log("Executed once");
}, 1000);
const timer = setInterval(() => {
console.log("Repeated execution");
}, 2000);
// To stop the interval later:
// clearInterval(timer);
The specified delays represent scheduling requests rather than guaranteed exact execution times.
46. What is the difference between Promise.all() and Promise.race()?
Both methods accept an iterable of Promises and return a new Promise, but their completion behaviour differs.
Promise.all() fulfils when all input Promises fulfil and rejects when an input Promise rejects.
Promise.race() settles as soon as one input Promise settles, whether fulfilled or rejected.
const first = Promise.resolve("A");
const second = Promise.resolve("B");
Promise.all([first, second]).then(result => {
console.log(result);
});
Output:
["A", "B"]
Promise.all() is useful when multiple independent asynchronous results are required before continuing.
47. What is the prototype in JavaScript?
A prototype is an object through which JavaScript objects can inherit properties and methods.
JavaScript uses prototype-based inheritance. When a property is not found directly on an object, the runtime can look for it along the object's prototype chain.
const person = {
greet() {
console.log("Hello");
}
};
const student = Object.create(person);
student.greet();
Output:
Hello
Prototypes help share methods between objects and form the foundation of JavaScript's inheritance model.
48. What are classes in JavaScript?
Classes provide a structured syntax for creating objects and working with inheritance. They were introduced in ES6 as a more convenient abstraction over JavaScript's prototype-based object model.
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
display() {
console.log(this.name, this.age);
}
}
const student = new Student("Arun", 22);
student.display();
Output:
Arun 22
Classes support constructors, instance methods, static methods, inheritance, and other object-oriented programming features.
49. What is the difference between synchronous and asynchronous execution in the event loop?
Synchronous statements execute directly on the call stack. Asynchronous callbacks are scheduled for later execution through the relevant runtime mechanisms.
For example, Promise callbacks are processed as microtasks, while timer callbacks are scheduled as tasks.
console.log("Start");
setTimeout(() => {
console.log("Timer");
}, 0);
Promise.resolve().then(() => {
console.log("Promise");
});
console.log("End");
Output:
Start
End
Promise
Timer
Even though the timer delay is zero, the synchronous code completes first, followed by the Promise microtask and then the timer task.
50. What is the Fetch API in JavaScript?
The Fetch API provides an interface for making network requests and receiving responses from servers.
It returns a Promise that fulfils with a Response object when a response is received.
async function getUsers() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
if (!response.ok) {
throw new Error("Request failed");
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error.message);
}
}
getUsers();
Fetch is commonly used to retrieve API data, submit information, and connect frontend applications with backend services. HTTP error responses such as 404 or 500 do not automatically reject the Fetch Promise, so checking response.ok is important.
51. What are JavaScript modules?
Modules allow developers to divide application code into separate files and reuse functionality through imports and exports.
JavaScript supports named exports, default exports, and corresponding import statements.
math.js
export function add(a, b) {
return a + b;
}
app.js
import { add } from "./math.js";
console.log(add(10, 20));
Output:
30
Modules improve code organisation, maintainability, and separation of responsibilities in larger applications.
52. What is strict mode in JavaScript?
Strict mode is a JavaScript execution mode that enables additional checks and changes certain language behaviours to help identify common programming mistakes.
It can be enabled using:
"use strict";
let age = 22;
console.log(age);
Strict mode prevents certain problematic operations, such as accidentally creating undeclared variables through assignment, and makes some silent errors throw exceptions.
JavaScript modules and class bodies automatically execute in strict mode.
53. What is debouncing in JavaScript?
Debouncing is a technique that delays function execution until a specified period has passed without another triggering event.
It is useful for search inputs, resize handlers, and other situations where frequent events should not cause unnecessary operations.
function debounce(callback, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
callback.apply(this, args);
}, delay);
};
}
const search = debounce((value) => {
console.log("Searching:", value);
}, 500);
search("Java");
search("JavaScript");
Only the final scheduled callback executes if no new call occurs during the delay period.
54. What is throttling in JavaScript?
Throttling is a technique that limits how frequently a function can execute within a specified time interval.
It is useful for scroll events, mouse movement, and resize operations where executing a function for every event may affect performance.
function throttle(callback, delay) {
let lastExecution = 0;
return function(...args) {
const now = Date.now();
if (now - lastExecution >= delay) {
lastExecution = now;
callback.apply(this, args);
}
};
}
Unlike debouncing, which waits until activity stops, throttling allows execution at controlled intervals while events continue occurring.
55. What is the difference between shallow copy and deep copy in JavaScript?
A shallow copy creates a new outer object but retains references to nested objects. A deep copy creates an independent copy of nested data, subject to the types of values being copied.
const original = {
name: "Arun",
address: {
city: "Trichy"
}
};
const shallow = { ...original };
shallow.address.city = "Chennai";
console.log(original.address.city);
Output:
Chennai
The nested address object is shared between the original and shallow copy.
For supported structured data, JavaScript provides structuredClone():
const deep = structuredClone(original);
deep.address.city = "Madurai";
console.log(original.address.city);
console.log(deep.address.city);
Output:
Chennai
Madurai
Deep copying requires care when objects contain functions, DOM nodes, or other values that are not supported by the chosen cloning method.
6. JavaScript Programming Interview Questions: Practical Coding Examples
Coding exercises help interviewers assess whether candidates can apply JavaScript concepts to real programming problems. Practise these programs independently and understand the logic behind each solution.
56. How do you reverse a string in JavaScript?
JavaScript provides array methods that can be used to reverse the characters of a string.
const text = "JavaScript";
const reversed = text
.split("")
.reverse()
.join("");
console.log(reversed);
Output:
tpircSavaJ
This approach works for simple strings, but splitting by UTF-16 code units may not correctly reverse every Unicode character, particularly complex emoji sequences.
57. How do you check whether a number is even or odd in JavaScript?
The modulo operator % returns the remainder after division.
const number = 14;
if (number % 2 === 0) {
console.log("Even");
} else {
console.log("Odd");
}
Output:
Even
A number is even when its remainder after division by two is zero.
58. How do you find the factorial of a number in JavaScript?
Factorial is the product of all positive integers from one to a given non-negative integer. The factorial of zero is one.
function factorial(number) {
let result = 1;
for (let i = 1; i <= number; i++) {
result *= i;
}
return result;
}
console.log(factorial(5));
Output:
120
This iterative solution takes O(n) time. A complete implementation should validate negative and non-integer inputs and account for JavaScript's numeric precision limits.
59. How do you check whether a string is a palindrome in JavaScript?
A palindrome reads the same forwards and backwards under the chosen comparison rules.
function isPalindrome(text) {
const reversed = text
.split("")
.reverse()
.join("");
return text === reversed;
}
console.log(isPalindrome("madam"));
console.log(isPalindrome("hello"));
Output:
true
false
This example uses a case-sensitive comparison and does not ignore spaces or punctuation.
60. How do you find the largest number in an array?
The Math.max() function can be combined with the spread operator to find the largest number in an array.
const numbers = [12, 45, 7, 89, 23];
const largest = Math.max(...numbers);
console.log(largest);
Output:
89
This approach is concise for reasonably sized arrays. For large collections, an iterative solution avoids spreading all elements into function arguments.
61. How do you remove duplicate elements from an array?
The Set object stores unique values, making it useful for removing duplicate elements.
const numbers = [1, 2, 2, 3, 1, 4];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers);
Output:
[1, 2, 3, 4]
This approach preserves the insertion order of the unique values.
62. How do you find the frequency of each element in an array?
A Map can store each element and its corresponding frequency.
const numbers = [1, 2, 2, 3, 1, 2];
const frequency = new Map();
for (const number of numbers) {
frequency.set(
number,
(frequency.get(number) || 0) + 1
);
}
console.log([...frequency]);
Output:
[[1, 2], [2, 3], [3, 1]]
This example demonstrates loops, maps, and conditional value updates.
63. How do you find the sum of all elements in an array?
The reduce() method can calculate the total by accumulating values from an array.
const numbers = [10, 20, 30, 40];
const sum = numbers.reduce(
(total, number) => total + number,
0
);
console.log(sum);
Output:
100
The initial value of zero ensures that the accumulation starts with a defined numeric value.
64. How do you find the second-largest unique number in an array?
A Set can remove duplicate values, and sorting can arrange the remaining values in descending order.
const numbers = [10, 25, 30, 25, 50, 40];
const uniqueNumbers = [...new Set(numbers)];
uniqueNumbers.sort((a, b) => b - a);
const secondLargest = uniqueNumbers[1];
console.log(secondLargest);
Output:
40
This approach requires at least two distinct values. For larger datasets, a single-pass algorithm can find the second-largest unique value without sorting the entire array.
7. How to Prepare for a JavaScript Technical Interview
Preparing for a JavaScript interview becomes easier when learning is divided into clear stages. Rather than memorising definitions, focus on understanding how the language behaves and applying concepts through practical exercises.
Build a strong foundation in JavaScript basics. Start with variables, data types, operators, conditions, loops, functions, and arrays. These topics are essential for solving beginner-level programming problems.
Understand functions and scope. Practise function declarations, arrow functions, callbacks, closures, hoisting, and variable scope. These concepts frequently appear in technical interviews because they explain how JavaScript executes code.
Learn modern JavaScript features. Understand ES6+ features such as let, const, template literals, destructuring, spread operators, rest parameters, modules, and optional chaining.
Practise DOM manipulation. Learn how to select HTML elements, update content, handle browser events, validate forms, and work with event propagation. These skills are particularly important for frontend development roles.
Understand asynchronous JavaScript. Study callbacks, promises, async/await, Fetch API, and the event loop. Practise explaining the execution order of programs containing timers and Promise callbacks.
Solve coding problems independently. Practise string reversal, palindrome checking, factorial calculation, array manipulation, duplicate removal, and frequency counting. Test different inputs rather than relying on a single example.
Build practical projects. Create beginner-friendly applications such as a to-do list, calculator, weather application using an API, form validation system, or simple expense tracker. These projects demonstrate how JavaScript works with HTML, CSS, browser events, and external data.
Prepare to explain your logic. During technical interviews, describe the problem, explain your approach, discuss why you selected a particular method, and consider possible edge cases.
Students looking for structured programming education and practical development preparation can explore the training opportunities offered by Well Spring Talent Solutions as part of their journey towards frontend and software development roles.
8. Common Mistakes Freshers Should Avoid in JavaScript Interviews
Knowing JavaScript syntax is only one part of interview preparation. Candidates should also understand how the language behaves in different situations.
One common mistake is confusing == and ===. These operators perform different comparison operations, and using loose equality without understanding type coercion can lead to unexpected results.
Another mistake is assuming that const makes an object completely immutable. It prevents reassignment of the variable binding, but properties of the referenced object can still be modified unless additional restrictions are applied.
Candidates should also avoid treating null and undefined as identical, confusing shallow copies with deep copies, or misunderstanding how closures retain access to variables from their surrounding scope.
Asynchronous JavaScript is another important area. Freshers should understand why Promise callbacks and timer callbacks may execute in different orders, how async/await works, and why network errors and HTTP error responses need appropriate handling.
For frontend roles, ignoring DOM manipulation, event bubbling, and event delegation can also create preparation gaps.
Finally, avoid memorising coding solutions without understanding their logic. Interviewers may change input values, introduce new conditions, or request a more efficient solution. Regular coding practice makes it easier to handle these variations confidently.
Frequently Asked Questions About JavaScript Interviews
1. Which JavaScript interview questions are commonly asked for freshers?
Freshers are commonly asked about variables, data types, functions, arrays, objects, loops, scope, hoisting, closures, and ES6 features. Technical interviews may also include DOM manipulation, promises, asynchronous programming, and basic JavaScript coding exercises.
2. How should beginners prepare for JavaScript interviews?
Beginners should start with JavaScript syntax, variables, operators, functions, arrays, and objects. They should then practise DOM manipulation, ES6 features, asynchronous programming, and common coding problems while building small web development projects.
3. Is JavaScript enough to get a fresher frontend developer job?
JavaScript is an essential frontend development skill, but employers commonly expect knowledge of HTML, CSS, responsive design, DOM manipulation, APIs, Git, and debugging. Some positions may also require experience with frameworks such as React or Vue.
4. What are the most important JavaScript concepts for technical interviews?
Important concepts include variable scope, hoisting, closures, this, functions, objects, arrays, promises, async/await, the event loop, DOM manipulation, and event handling. Candidates should also understand modern ES6+ features.
5. Do JavaScript interviews include coding questions?
Yes. Many JavaScript technical interviews include coding exercises involving strings, arrays, objects, loops, functions, and mathematical operations. Candidates may also be asked to predict output, debug code, or explain asynchronous execution.
6. What is the difference between JavaScript and TypeScript?
JavaScript is a dynamically typed programming language, while TypeScript adds a static type system and additional development features on top of JavaScript. TypeScript code is generally transformed into JavaScript before execution in standard browser environments.
7. How can freshers improve their confidence in JavaScript technical interviews?
Freshers can improve their confidence by practising coding problems, understanding JavaScript fundamentals, building interactive web projects, and participating in mock interviews. Explaining the reasoning behind each solution is just as important as writing correct code.
Conclusion
JavaScript is an essential programming language for modern web development, offering the flexibility to build interactive frontend experiences and complete application solutions. Understanding its fundamentals, functions, arrays, objects, ES6 features, DOM manipulation, asynchronous programming, and event loop helps aspiring developers build a strong technical foundation.
These JavaScript Interview Questions and Answers provide a structured preparation resource covering basic concepts, advanced topics, browser functionality, and practical coding exercises.
Instead of memorising every answer, write the programs independently, test different inputs, and understand how JavaScript processes each operation. Consistent coding practice, practical project experience, and the ability to explain technical concepts clearly can help freshers approach JavaScript developer interviews with greater confidence.