JavaScript Array Interview Questions PDF By ScholarHat
1. Top 50 JavaScript Array Questions and Answer
If you're preparing for a JavaScript interview, having a strong understanding of JavaScript
Arrays is essential. You might be asked to explain various Array Methods in JavaScript,
their properties, and code implementations using JavaScript's built-in Array
functionalities. Being familiar with array manipulation, iteration, filtering, and sorting,
as well as understanding performance and immutability, is highly beneficial.
In this JavaScript tutorial, we’ll explore the top JavaScript Array interview questions with clear
examples and explanations. By the end, you’ll be ready to confidently tackle any array-related
question and apply these concepts in real-world scenarios.
2. JavaScript Array Interview Questions and Answers for
Freshers
1. What does the
2. What is the method used for?
method do in JavaScript?
indexOf()
concat()
Try it Yourself >>
The concat() method is used to join two or more arrays together. It does not change the original
arrays. Instead, it creates and returns a new array that contains all the elements of the arrays you
passed to it.
[1, 2, 3, 4, 5, 6]
let arr1 = [1, 2, 3]; let arr2 = [4, 5,
6]; let result = arr1.concat(arr2);
console.log(result);
Output
3. Try it Yourself >>
Try it Yourself >>
The push() method adds one or more elements to the end of an array and gives you back the new
length of the array.
The pop() method removes the last element from an array and gives you that element. The
array's length will also decrease.
The indexOf() method helps you find the position of the first occurrence of a specified element
in an array. If the element is not found, it will return -1.
2
[1, 2, 3, 4, 5]
let arr = [1, 2, 3];
arr.push(4, 5);
console.log(arr);
let arr = [10, 20, 30];
let lastElement = arr.pop();
console.log(lastElement);
console.log(arr);
let arr = [10, 20, 30, 40];
let index = arr.indexOf(30);
console.log(index);
Output
Output
3. How does the
4. What does the method do?
method work?
pop()
push()
4. Output
Output
1
[2, 3]
30
[10, 20]
let arr = [2, 3, 4];
arr.unshift(1);
console.log(arr);
let arr = [1, 2, 3];
let firstElement = arr.shift();
console.log(firstElement);
console.log(arr);
5. What is the
6. How does the
method?
method work?
shift()
unshift()
Try it Yourself >>
Try it Yourself >>
Try it Yourself >>
The shift() method removes the first element from an array and gives you that element. It also
reduces the size of the array.
The unshift() method adds one or more elements to the beginning of an array and gives back
the new length of the array.
5. Output
Output
[1, 2, 3, 4]
[20, 30, 40]
let arr = [10, 20, 30, 40, 50];
let newArr = arr.slice(1, 4);
console.log(newArr);
let arr = [10, 20, 30, 40, 50];
arr.splice(2, 2, 100, 200);
console.log(arr);
7. What is the
8. What does the
method?
method do?
slice()
splice()
Try it Yourself >>
Try it Yourself >>
The splice() method changes the contents of an array. You can use it to remove, add, or replace
elements at any position in the array. Unlike other methods, it directly modifies the original array.
The slice() method returns a new array that contains a portion of the original array. It does not
modify the original array. You pass the start index and end index (exclusive) to select the portion
you want.
HTML to PDF
6. Output
Output
Output
[5, 4, 3, 2, 1]
[10, 20, 40, 100]
[10, 20, 100, 200, 50]
let arr = [1, 2, 3, 4, 5];
arr.reverse();
console.log(arr);
let arr = [40, 10, 100, 20];
arr.sort((a, b) => a - b);
console.log(arr);
10. What is the
9. How does the
11. What does the method do?
method used for?
method work?
sort()
join()
reverse()
Try it Yourself >>
Try it Yourself >>
The reverse() method reverses the order of the elements in the array. It changes the array in
place and returns the reversed array.
The sort() method is used to arrange the elements of an array in ascending order. If you want a
different order, you can provide a custom function to control how the sorting is done.
The join() method combines all elements of an array into a single string, using a separator like a
comma, space, or custom string. If no separator is provided, it defaults to a comma.
7. Output
Output
[2, 4]
10-20-30
let arr = [10, 20, 30];
let result = arr.join("-");
console.log(result);
false
let numbers = [2, 4, 6];
let result = numbers.every(num => num % 2 === 0);
let numbers = [1, 2, 3, 4, 5];
let result = numbers.filter(num => num % 2 === 0);
console.log(result);
true
forEach()
13. How does the
14. What does the
12. What is the difference between
method do?
method work?
and
every()
filter()
map() forEach()?
Try it Yourself >>
Try it Yourself >>
every() checks if all elements in an array satisfy a condition. It returns
otherwise .
map() creates a new array by applying a function to each element, whereas
executes a function on each element without returning a new array.
The filter() method creates a new array with elements that pass a test in a callback function. If
no elements match, it returns an empty array.
just
if all match,
8. Output
Output
true
false
console.log(result);
false
let numbers = [1, 3, 5];
let result = numbers.some(num => num % 2 === 0);
console.log(result);
let numbers = [1, 2, 3];
let sum = numbers.reduce((acc, num) => acc + num, 0);
true
16. What is the
15. How does the method work?
method used for?
reduce()
some()
Try it Yourself >>
Try it Yourself >>
some() checks if any element in the array satisfies a condition. It returns
otherwise .
The reduce() method reduces an array to a single value by applying a function to an accumulator
and each element.
if any match,
9. Output
Output
Output
6
-4
[1, 2, 3]
console.log(sum);
An array-like object has a length
push(). Examples include NodeList
function example() {
}
example(1, 2, 3);
console.log(arguments);
reduceRight() works like reduce()
let numbers = [1, 2, 3];
let result = numbers.reduceRight((acc, num) => acc - num, 0);
console.log(result);
17. What is the method?
18. What is an array-like object in JavaScript?
reduceRight()
Try it Yourself >>
Try it Yourself >>
Try it Yourself >>
, but it processes the array from right to left.
property and indexed elements but lacks array methods like
and the arguments object.
10. 19. What is the
20. How does the
21. What is the difference between
method work?
method used for?
and
find()
from()
let var?
The
is found.
Try it Yourself >>
Try it Yourself >>
is block-scoped, while is function-scoped.
method returns the first element that satisfies a condition, or if no match
creates a new array from an array-like or iterable object, such as a string or
prevents redeclaration in the same scope.
3
find()
let var
let a = 10;
{
let a = 20;
console.log(a); // 20
["h", "e", "l", "l", "o"]
Array.from()
NodeList.
let str = "hello";
let result = Array.from(str);
console.log(result);
let numbers = [1, 2, 3, 4];
let result = numbers.find(num => num > 2);
console.log(result);
let
undefined
Output
Output
11. Output
Output
2
0
10
[1, 2, 3, 4]
function greet() {
let person = {
firstName: 'John',
lastName: 'Doe'
};
}
console.log(a); // 10
const numbers = [1, 2, 3];
numbers.push(4); // Allowed
// numbers = [4, 5, 6]; // Error: Assignment to constant variable
console.log(numbers);
23. What is the
22. What is the purpose of
method in JavaScript?
in JavaScript?
bind()
const
Try it Yourself >>
Try it Yourself >>
The bind() method allows you to create a new function with its this context explicitly set to a
specified object. This is particularly useful when passing functions as callbacks, ensuring that
the
function retains its original context regardless of how it is invoked.
const defines a variable whose value cannot be reassigned, though the contents of objects or
arrays can still be modified.
12. Output
Output
7
Hello, John Doe
this
let sum = (a, b) => a + b;
console.log(sum(3, 4));
let greetPerson = greet.bind(person);
greetPerson();
console.log('Hello, ' + this.firstName + ' ' + this.lastName);
}
25. What is a promise in JavaScript?
A promise is an object representing the eventual completion or failure of an asynchronous
operation. It can be in one of three states: pending, fulfilled, or rejected. Promises are commonly
used to handle asynchronous operations like API calls.
24. What are arrow functions in JavaScript?
Arrow functions in JavaScript provide a shorter syntax for writing functions. They also handle the
Try it Yourself >>
Try it Yourself >>
keyword differently than regular functions, inheriting this from the surrounding context.
13. Output
fetchData();
Operation was successful!
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve('Operation was successful!');
} else {
}
} ) ;
reject('Operation failed');
async function fetchData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
}
promise.then(result => console.log(result)).catch(error => console.log(error));
26. What is the syntax in JavaScript?
async/await
Try it Yourself >>
The async/await syntax is used to work with asynchronous code in a more readable way. asyncIt
makes a function return a promise and await pauses the function execution until the promise is
resolved.
14. 27. What is the
29. What is a closure in JavaScript?
A closure is a function that has access to its own scope, the outer function's scope, and the
global scope. This allows functions to remember and access variables from their lexical
environment even after the outer function has finished execution.
28. What is event delegation in JavaScript?
Event delegation is a technique for handling events at a higher level in the DOM rather than
attaching event listeners to individual elements. This improves performance, especially
when dealing with dynamically added elements.
keyword in JavaScript?
this
Try it Yourself >>
Try it Yourself >>
Read More: This Keyword in Java
The this keyword refers to the context in which a function is called. In regular functions, this
refers to the global object (or undefined in strict mode), while in object methods, it refers to the
object itself.
function outer() {
let counter = 0;
return function inner() {
counter++;
console.log(counter);
};
document.getElementById('parent').addEventListener('click', function(event) {
if (event.target && event.target.matches('button.classname')) {
}
});
console.log('Button clicked!');
15. Output
Output
}
1
2
[1, 4, 9, 16]
let increment = outer();
increment();
increment();
let numbers = [1, 2, 3, 4];
let squares = numbers.map(num => num * num);
console.log(squares);
31. What is the
32. What is the
30. What is the difference between and
method?
method?
==
Array.prototype.map()
Array.prototype.filter()
===?
Try it Yourself >>
Try it Yourself >>
Read More: Understanding Type Casting or Type Conversion in C#
The map() method creates a new array populated with the results of calling a provided function
on every element in the calling array. It doesn’t change the original array.
== is the equality operator that compares values, allowing type coercion. === is the strict equality
operator that compares both values and types, without allowing type conversion.
16. The
(in milliseconds).
Try it Yourself >>
Try it Yourself >>
Try it Yourself >>
The reduce() method applies a function against an accumulator and each element in the array to
reduce it to a single value.
function is used to execute a function or code snippet after a specified delay
The filter() method creates a new array with all elements that pass the test implemented by
the provided function. It doesn’t change the original array.
10
[2, 4]
setTimeout()
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum);
setTimeout(() => console.log('Hello, world!'), 2000);
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers);
Output
Output
33. What is the
34. What is the function?
method?
setTimeout()
Array.prototype.reduce()
17. Output
Output
Output
Hello World
setInterval()
Hello, world! (after 2 seconds)
Repeating message (every second)
export import
// file1.js
export const greeting = 'Hello World';
// file2.js
import { greeting } from './file1.js';
console.log(greeting);
setInterval(() => console.log('Repeating message'), 1000);
35. What is the
What are JavaScript modules?
Ans: JavaScript modules allow you to split code into separate files, making it easier to manage
and maintain. Modules can export and import Variables in JavaScript, functions, or objects from
function?
setInterval()
The
call.
Try it Yourself >>
Try it Yourself >>
function calls a function repeatedly with a fixed time delay between each
other files using the and keywords.
JavaScript Array Interview Questions for Experienced
18. 40. What is
37. What is the
38. Explain the concept of
and
in JavaScript?
in JavaScript.
39. What are higher-order functions in JavaScript?
A higher-order function is a function that takes one or more functions as arguments or returns a
function as its result. These are common in functional programming.
in JavaScript?
throttling
Event Loop
hoisting
debouncing
Try it Yourself >>
Hoisting is JavaScript’s behavior of moving declarations to the top of their containing scope
before code execution. Variables declared with var are hoisted, while those declared with let and
const are hoisted but remain uninitialized until the code execution reaches them.
Throttling and debouncing are techniques used to limit the number of times a function is
executed. Throttling ensures that a function is called no more than once at every specified time
The event loop is a fundamental part of JavaScript's concurrency model. It allows JavaScript to
perform non-blocking operations by executing the code, collecting events, and executing sub-
tasks in the order they are received, allowing asynchronous tasks to be handled.
10
function multiplyBy(factor) {
return function (num) {
return num * factor;
};
}
const double = multiplyBy(2);
console.log(double(5)); // 10
Output
19. Try it Yourself >>
Read More: Garbage Collection in C#
null represents the intentional absence of any value, while
declared but has not yet been assigned a value. In other words,
uninitialized variables.
A Map object holds key-value pairs where both the keys and values can be of any type. Map in
JavaScriptremember the insertion order of their elements and offer better performance when
frequent additions and removals are needed compared to regular objects.
interval while debouncing ensures the function is only executed after a specified delay after the
last call.
The prototype chain is a mechanism that allows objects to inherit properties and methods from
other objects. Every object in JavaScript has a prototype, and when you try to access a property
or method, the search for it happens in the prototype chain if it doesn't exist in the object itself.
means a variable has been
is the default value of
A WeakMap is a collection of key-value pairs where the keys must be objects, and the values can
be any type. WeakMaps do not prevent garbage collection, meaning if there are no other
references to the key object, it can be garbage collected.
42. What is a
41. What is the
44. What is the
43. What is the difference between
in JavaScript?
object in JavaScript?
and
in JavaScript?
Map
WeakMap
Prototype Chain
null undefined?
let map = new Map();
map.set('name', 'John');
map.set('age', 30);
console.log(map.get('name')); // John
undefined
undefined
Output
20. John
requestAnimationFrame(animate);
Animating... (calls indefinitely)
setTimeout() setInterval()
function animate() {
// Animation code
console.log('Animating...');
requestAnimationFrame(animate);
}
46. What is
47. What is a
45. What are async iterators in JavaScript?
Async iterators are a type of iterator that allows you to loop over asynchronous data. They work
with the for-await-of loop and can handle promises that resolve with asynchronous data
streams.
in JavaScript?
48. How can you handle errors in JavaScript?
in JavaScript?
Try it Yourself >>
A Service Worker is a JavaScript script that runs in the background and manages caching, push
notifications, and background sync for web apps, enabling offline functionality and improving
performance.
The requestAnimationFrame() method tells the browser to call a specified function to update an
animation before the next repaint, ensuring smooth animations. It’s more efficient than using
or for animations.
Service Worker
requestAnimationFrame()
Output
21. Try it Yourself >>
Try it Yourself >>
Web Workers allow JavaScript to run scripts in background threads, enabling you to perform
complex computations without blocking the main thread, improving the performance of web
applications.
JavaScript provides the try...catch block to handle exceptions. You can try executing a block
of code, and if an error occurs, it can be caught and handled inside the catch block.
Object.freeze() is used to make an object immutable, meaning its properties cannot be
modified, added, or deleted. This can prevent accidental modifications to objects.
John
Error: [Error message here]
try {
let result = riskyFunction();
} catch (error) {
console.error('Error:', error.message);
}
let obj = { name: 'John' };
Object.freeze(obj);
obj.name = 'Jane'; // This will not change the name
console.log(obj.name); // John
Output
Output
50. What is
49. What are in JavaScript?
in JavaScript?
Web Workers
Object.freeze()
22. Try it Yourself >>
Read More: JavaScript Interview Questions & Answers
The second largest element in an array can be found by iterating through the array while keeping
track of the largest and second largest elements in a single pass.
Removing duplicates from an array can be efficiently done using a Set, which only stores unique
values, or by filtering elements based on their first occurrence.
Q 51. How do you find the second largest element in an array?
Q 52. How do you remove duplicates from an array in JavaScript?
Output
45
function secondLargest(arr) {
}
console.log(secondLargest([10, 20, 4, 45, 99]));
let first = -Infinity, second = -Infinity;
for (let num of arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num < first) {
second = num;
}
}
return second;
function removeDuplicates(arr) {
} console.log(removeDuplicates([1, 2, 3, 2, 4, 5, 1]));
return [...new Set(arr)];
23. Output
Output
3
[1, 2, 3, 4, 5]
function rotateArray(arr, k) {
}
console.log(rotateArray([1, 2, 3, 4, 5], 2));
k = k % arr.length;
return [...arr.slice(-k), ...arr.slice(0, -k)];
function missingNumber(arr, n) {
} console.log(missingNumber([1, 2, 4, 5, 6], 6));
let total = (n * (n + 1)) / 2;
let sum = arr.reduce((acc, num) => acc + num, 0);
return total - sum;
Q 54. How do you rotate an array to the right by k places?
Rotating an array to the right by k places means shifting elements to the right while wrapping
around. This can be done using slicing and concatenation.
Q 53. How do you find the missing number in an array of 1 to N?
The missing number in an array can be found using the sum formula for the first N natural
numbers and subtracting the sum of the given array elements.
Try it Yourself >>
Try it Yourself >>
Try it Yourself >>
24. Output
Output
[3, 4]
[4, 5, 1, 2, 3]
function arrayIntersection(arr1, arr2) {
} console.log(arrayIntersection([1, 2, 3, 4], [3, 4, 5, 6]));
let set1 = new Set(arr1);
return arr2.filter(num => set1.has(num));
function maxSubarraySum(arr) {
}
console.log(maxSubarraySum([-2, 1, -3, 4, -1, 2, 1, -5, 4]));
let maxSum = arr[0], currentSum = arr[0];
for (let i = 1; i < arr.length; i++) {
currentSum = Math.max(arr[i], currentSum + arr[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
Q 55. How do you find the intersection of two arrays?
The intersection of two arrays consists of elements that appear in both arrays. This can be
efficiently achieved using a Set for quick lookups.
Q 56. How do you find the subarray with the maximum sum
(Kadane's Algorithm)?
Finding the maximum sum subarray is efficiently solved using Kadane's Algorithm, which keeps
track of the current maximum sum and updates the global maximum.
Try it Yourself >>
Try it Yourself >>
25. Output
Test your skills by following MCQs
Q 1: What is the correct way to create an array in JavaScript?
6
Summary
This tutorial covered the top 50 JavaScript Array interview questions and answers, categorized
based on experience levels: fresher, intermediate, and experienced. It provides a comprehensive
understanding of key concepts of JavaScript Array, from basic operations to advanced array
methods and techniques. By reviewing these questions, you'll be well-prepared to excel in
interviews and showcase your proficiency with arrays in JavaScript.
Previous
let arr = []
let arr = {}
let arr = ()
let arr = <>
Next
Dear learners, we come up with MCQs on JavaScript Array that will surely help you to enhance
your knowledge.
Unlock your JavaScript skills with Scholarhat's JavaScript Course! Enroll now and master
JavaScript to create efficient, scalable web applications.