
10 JavaScript coding interview questions — Part 1
In this article, we will explore 10 frequently asked JavaScript coding interview questions. This marks the initiation of the JavaScript interview series, where each installment, comprising five parts in total, unveils a set of 10 JavaScript coding questions.
The other parts of this series are:
Question 1: Can you write a function in JavaScript to reverse the order of words in a given string?
const reversedString = str => str.split(' ').reverse().join(' ');
In this function, the input string is split into an array of words using the split(' ')
method. Then, the order of the words in the array is reversed with reverse()
. Finally, the reversed array is joined back into a string using join(' ')
. This concise line elegantly achieves the reversal of word order in the given string.
Question 2: Can you write a function in JavaScript to remove duplicate elements from an array?
const uniqueArray = arr => [...new Set(arr)];
This concise function utilizes the Set
object in JavaScript, which automatically removes duplicate values. The spread operator (...
) is then used to convert the set back into an array. This elegant solution capitalizes on the unique property of sets, simplifying the process of eliminating duplicates from an array.
Question 3: Can you write a function in JavaScript to merge two objects without overwriting existing properties?
const mergeObjects = (obj1, obj2) => ({ ...obj1, ...obj2 });
This function utilizes the spread (...
) operator within an object literal to merge the properties of obj1
and obj2
. The order is important; properties of obj2
will overwrite properties of obj1
with the same name. This one-liner is effective for creating a new object that contains the combined properties of both objects without modifying the original objects.
Question 4: Can you write a function in JavaScript to get the current date in the format “YYYY-MM-DD”?
const currentDate = () => new Date().toISOString().split('T')[0];
In this function, the Date
object is used to get the current date and time. The toISOString
method is then employed to convert the date to a string in the ISO 8601 format. Finally, the string is split at the 'T' character, and only the part before 'T' (which represents the date) is extracted. This provides the current date in the desired "YYYY-MM-DD" format.
Question 5: Can you write a function in JavaScript to calculate the cumulative sum of an array?
Cumulative sums, or running totals, are used to display the total sum of data as it grows with time (or any other series or progression). This lets you view the total contribution so far of a given measure against time. An example of a cumulative sum is: Input array => 10, 15, 20, 25, 30. Output array => 10, 25, 45, 70, 100.
const cumulativeSum = arr => arr.reduce((acc, num) => [...acc, acc.length ? acc[acc.length - 1] + num : num], []);
In this function, the reduce
method is employed to iterate over the array, maintaining an accumulator (acc
) that stores the cumulative sum at each step. The spread operator (...
) is used to create a new array at each step, ensuring that the original array remains unchanged. This approach provides a concise way to calculate the cumulative sum of the input array.
Question 6: Can you write a function in JavaScript to split an array into chunks of a specified size?
const chunkArray = (arr, size) => Array.from({ length: Math.ceil(arr.length / size) }, (_, i) => arr.slice(i * size, i * size + size));
This one-liner function uses Array.from
to create a new array based on the length of the original array divided by the specified chunk size. The arrow function inside Array.from
then uses slice
to extract chunks of the array, ensuring that the chunks do not exceed the array's boundaries.
Question 7: Can you write a one-liner in JavaScript to find the longest consecutive sequence of a specific element in an array?
To enhance comprehension of this idea, let’s delve into an illustration. Consider a sequence comprising 10 elements, such as (1, 2, 3, 7, 8, 9, 4, 5, 6). In this scenario, the longest consecutive subsequence would be 3456, encompassing a total of four elements.
const longestConsecutiveSequence = (arr, element) => Math.max(...arr.join('').split(element).map(group => group.length));
In this simple function, the array is first joined into a single string, then split using the specified element. The resulting array consists of groups where the element occurs consecutively. The map
function is used to transform this array into an array of lengths of consecutive sequences, and Math.max(...)
finds the length of the longest consecutive sequence.
Question 8: Can you write a function in JavaScript to transpose a 2D matrix?
Creating a program to determine the transpose of a matrix involves the manipulation of its rows and columns. Essentially, the transpose is derived by converting the elements at position A[i][j] to A[j][i] for a matrix of size N by M, where N represents the number of rows and M represents the number of columns. This transformation entails swapping the roles of rows and columns, resulting in a rearranged matrix.
const transposeMatrix = matrix => matrix[0].map((col, i) => matrix.map(row => row[i]));
This function uses the map
function twice to iterate over the rows and columns of the matrix. The outer map
iterates over the columns, and the inner map
iterates over the rows. By swapping the indices during the inner map
, the original matrix is effectively transposed.
Question 9: Can you write a function in JavaScript to convert a string containing hyphens and underscores to camel case?
Camel case refers to the stylistic convention in which a compound word or phrase is devoid of spaces or punctuation. Rather than employing spaces or punctuation marks, each distinct word within the compound is demarcated by the use of either lowercase or uppercase letters. For instance, the transformation of the string “secret_key_one” into camel case results in “secretKeyOne.”
const toCamelCase = str => str.replace(/[-_](.)/g, (_, c) => c.toUpperCase());
This function uses the replace
method with a regular expression to match hyphens or underscores followed by any character. The callback function within replace
converts the matched character to uppercase, effectively transforming the string to camel case.
Question 10: Can you write a line of code in JavaScript to swap the values of two variables without using a temporary variable?
[a, b] = [b, a];
This simple line of code uses destructuring assignment to swap the values of a
and b
without the need for a temporary variable. The right-hand side [b, a]
creates a new array with the values of b
and a
, and the destructuring assignment [a, b]
assigns these values back to a
and b
respectively.
The other parts of this series are:
Thanks for reading this article!
UPDATE:
I’ve recently published my free book in preparing for JavaScript interviews. The book contains 100 frequently asked JavaScript interview questions with answers. The free book is available here: