Javascript Interview Questions 2024: Coding Interview - Part 2

In this post I will list some common JavaScript coding interview questions. This is the sieries of posts, in which I’will list most commont questions with answers and explanations to them. I offer you to try to answer the question by yourself and then look up the answer

1. Write a function which implements a range

1
// Example
2
3
console.log(range(1, 50)); // [1,2,3,4, ... , 50]
Answer 1
1
// Answer
2
const range = (start, end) => {
3
const arr = [];
4
for (let i = start; i <= end; i++) {
5
arr.push(i);
6
}
7
return arr;
8
};

Explanation:

This JavaScript code defines a function called range that takes two numbers as input: start and end. The function creates an array and fills it with numbers starting from start and ending with end. Here’s a step-by-step explanation of how it works:

  • The function range is defined using the arrow function syntax.
  • Inside the function, an empty array called arr is created to store the numbers within the specified range.
  • A for loop is used to generate the numbers from start to end and store them in the array.
    • The loop starts by setting the variable i equal to start.
    • It checks if i is less than or equal to end before running the code inside the loop.
    • If the condition is true, it adds i to the array using the push() method.
    • Then it increments i by 1 and goes back to the beginning of the loop.
  • Once the loop finishes, the function returns the array containing all the numbers between start and end.
Answer 2
1
// Answer
2
const range = (start, end) => {
3
return [...Array(end - start).keys()].map((el) => el + start);
4
};

Explanation:

This JavaScript code is an alternative implementation of the range function using a different approach. It creates and returns an array containing integers between start and end inclusively.

  • Array Creation: The code uses the spread operator (…) and Array constructor to create a new array. The size of the array is determined by subtracting start from end, resulting in end - start. This ensures that the new array contains the appropriate number of elements.
  • Array Population: The .keys() method is called on the newly created array to extract an iterator containing the keys of the array. The spread operator is used again to transform the iterator into an array of keys, which in this case are sequential integers starting from 0.
  • Mapping Values: The .map() method is applied to the array of keys to create a new array. For each key el, el + start is calculated, which shifts the index values so that they start from start instead of 0. This creates an array containing integers from start to end.

Resources

MDN Array Constructor

MDN .keys()

MDN .map()

2. Write a function wich implements shuffle (randomly reorders items inside the array)

What will be logged to the console in first and second examples?

1
// Example
2
const testArr = [1, 2, 3, 4, 5];
3
4
console.log(shuffle(testArr)); // [2,5,3,1,4]
Answer 1
1
// Answer
2
// A: Fisher-Yates sorting algorithm
3
const shuffleArr = (arr) => {
4
for (let i = arr.length - 1; i > 0; i--) {
5
const j = Math.floor(Math.random() * (i + 1));
6
[arr[i], arr[j]] = [arr[j], arr[i]];
7
}
8
return arr;
9
};

Explanation:

This JavaScript code defines a function named shuffleArr that takes an array (arr) as an input parameter and shuffles its elements randomly. The shuffling is done in-place, meaning the original array is modified. Here’s a detailed explanation of how the code works:

  • Loop Initialization: The code initializes a for loop with the loop variable i set to arr.length - 1, which is the index of the last element in the array. The loop will iterate backward until i becomes 0, ensuring that each element in the array is visited once.
1
for (let i = arr.length - 1; i > 0; i--)
  • Random Index Selection: Within each loop iteration, a random index j is generated using Math.random(), which produces a random number between 0 and 1. This random number is then multiplied by i + 1 to ensure j falls within the range of 0 to i (inclusive). Finally, Math.floor() is applied to round down the result, giving j an integer value.
1
const j = Math.floor(Math.random() * (i + 1));
  • Element Swapping: The code uses array destructuring to swap the elements at indexes i and j. The [arr[i], arr[j]] = [arr[j], arr[i]] expression creates a new array [arr[j], arr[i]] with the elements in reverse order and assigns it to [arr[i], arr[j]].
1
[arr[i], arr[j]] = [arr[j], arr[i]];

In summary, the shuffleArr function randomizes the order of elements in the input array (arr) by iteratively swapping each element with a randomly selected element in the unshuffled portion of the array.

Answer 2
1
// Answer
2
const shuffleItems = (items) => {
3
return items
4
.map((item) => ({ sort: Math.random(), value: item }))
5
.sort((item1, item2) => item1.sort - item2.sort)
6
.map((a) => a.value);
7
};

Explanation:

  • First .map(): The code uses the .map() method to iterate through each item in the input array. Within the callback function, each item is transformed into an object with two properties: sort and value. The sort property contains a random number generated by Math.random(), and the value property holds the original item from the input array.
1
return items.map((item) => ({ sort: Math.random(), value: item }));
  • .sort(): The transformed array is then sorted using the .sort() method. The comparison function provided to .sort() compares the sort property of two items, item1 and item2, ensuring that the array is sorted in ascending order based on these random numbers.
1
return items
2
.map((item) => ({ sort: Math.random(), value: item }))
3
.sort((item1, item2) => item1.sort - item2.sort);
  • Second .map(): After the array is sorted, another .map() method is used to extract only the value property from each object, returning the original items in a shuffled order.
1
return items
2
.map((item) => ({ sort: Math.random(), value: item }))
3
.sort((item1, item2) => item1.sort - item2.sort)
4
.map((a) => a.value);

By assigning a random number to each item and sorting the array based on those numbers, the function ensures that each possible permutation of the input array is equally likely.

3. Find the number of occurences of a minimum value in the list

1
//Example
2
console.log(findMinOccur([1, 1, 2, 1, 3, 5])); // 3
Answer
1
// Answer
2
const findMinOccur = (arr) => {
3
const minVal = Math.min(...arr);
4
return (occNum = arr.filter((item) => item === minVal).length);
5
};

Explanation:

This JavaScript code defines a function named findMinOccur that takes an array (arr) as input and returns the count of occurrences of the smallest element within the array. The code utilizes built-in JavaScript methods to achieve this functionality. Here’s a breakdown of how the code works:

  • Finding the Minimum Value: Using the spread operator (…), the Math.min() method is applied to the input array. This function returns the smallest value within the array, which is assigned to the minVal variable.
1
const minVal = Math.min(...arr);
  • Filtering and Counting Occurrences: The arr.filter() method is used to filter the input array and create a new array containing only the elements equal to minVal. Then, the .length property of this filtered array is assigned to the occNum variable, which represents the count of the smallest element’s occurrences within the input array.
1
return (occNum = arr.filter((item) => item === minVal).length);

In summary, the findMinOccur function identifies the smallest element within the input array (arr) and returns the count of its occurrences. The function achieves this by finding the minimum value (minVal), filtering the array to find matching elements, and calculating the count based on the length of the filtered array.

4. What will be looged to the console?

1
// Example 1
2
function getItem() {
3
console.log(this);
4
}
5
getItem();
Answer
1
// Answer
2
window or undefined in stict mode

Explanation:

When the given JavaScript code is executed, the value logged to the console will be window in normal mode and undefined in strict mode. Here’s the explanation:

Normal Mode:

In normal mode, the getItem() function is called without any specific context (this) provided. In such cases, JavaScript sets the this value to the global object, which is the window object in a browser environment. So when console.log(this) is executed inside the getItem() function, it logs the window object to the console.

Strict Mode:

In strict mode, the behavior of this changes when a function is called without a specific context. In this case, this remains undefined instead of referring to the global object.

So when the getItem() function is called in strict mode, console.log(this) logs undefined to the console, indicating that no specific context was provided.

1
// Example 2
2
const item = {
3
title: "Ball",
4
getItem() {
5
console.log("this", this);
6
},
7
};
Answer
1
// Answer
2
[object];

Explanation:

When the given JavaScript code is executed, the value logged to the console will be Object. This happens because of the way the getItem() method is defined and called within the item object. Here’s the explanation:

  • Object Definition: The code starts by defining an object literal named item. This object has a title property with the value “Ball” and a method named getItem().
  • Method Invocation: The getItem() method is called as item.getItem(). In this case, getItem() is invoked as a method of the item object. When a method is called in this way, JavaScript sets the this value to the object on which the method is called. Console Log Output: Inside the getItem() method, console.log(“this”, this) is executed. Since this refers to the item object in this context, the output will be Object .
1
// Example 1
2
class Item {
3
title = "Ball";
4
getItem() {
5
console.log(this);
6
}
7
}
8
const item2 = new Item();
9
item2.getItem();
Answer
1
// Answer
2
new insance of Item obj

Explanation:

When the given JavaScript code is executed, the value logged to the console will be an instance of the Item class, specifically the object stored in the item2 variable. This happens due to the way the getItem() method is defined within the Item class and how it is invoked on an instance of the class. Here’s the explanation:

  • Class Definition: The code starts by defining a class named Item using the ES6 class syntax. This class has a title property initialized to “Ball” and a method named getItem().
  • Object Instantiation: A new instance of the Item class is created using the new keyword, and this instance is stored in the item2 variable.
  • Method Invocation: The getItem() method is called on the item2 object as item2.getItem(). When a method is called on an object created from a class, JavaScript sets the this value to the object on which the method is called.
  • Console Log Output: Inside the getItem() method, console.log(this) is executed. Since this refers to the item2 object in this context, the output will be the item2 object, which is an instance of the Item class.

Resources

MDN this keyword

JsInfo - this keyword

5. Classes

Task 1: Design a class for employee which takes id and name during construction of object and has a salary property.

Answer
1
// Answer
2
class Employee {
3
constructor(id, name) {
4
if (!id || !name) {
5
throw new Error("Employee name and id are mandatory");
6
}
7
this.name = name;
8
this.id = id;
9
}
10
11
getName() {
12
return this.name;
13
}
14
15
getId() {
16
return this.id;
17
}
18
19
setSalary(salary) {
20
this.salary = salary;
21
}
22
23
getSalary() {
24
return this.salary;
25
}
26
}
27
const emlp1 = new Employee(29, "Ole");
28
29
console.log(emlp1.getName());
30
console.log(emlp1.getId());
31
emlp1.setSalary(65000);
32
console.log(emlp1.getSalary());

Task 2: Create a class of Manager which is employee but can have a department.

Answer
1
class Manager extends Employee {
2
setDepartment(department) {
3
this.department = department;
4
}
5
6
getDepartment() {
7
return this.department;
8
}
9
}

6. Implement a debounce function

Answer
1
// Answer
2
const debounce = (fn, delay = 300) => {
3
let timer;
4
return function (...args) {
5
clearTimeout(timer);
6
7
timer = setTimeout(() => {
8
fn(...args);
9
}, delay);
10
};
11
};
12
13
const inputRes = (arg) => {
14
console.log(`The arg is ${arg}`);
15
};
16
17
const tryIt = debounce(inputRes, 2000);
18
19
tryIt("LOL");
20
tryIt("LOL");
21
tryIt("LOL");
22
tryIt("LOL"); // only this one will be executed after 2sec of delay

Explanation:

This JavaScript code demonstrates the concept of debouncing, which is a technique used to delay the execution of a function until a certain amount of time has passed since the function was last called. This is often used in scenarios like handling user input events, such as keypresses, to prevent costly operations from being performed too frequently.

  • debounce Function: The debounce function is defined as a higher-order function, which means it returns another function as its output. It takes two arguments: fn, which is the function to be debounced, and an optional delay argument (default value: 300 milliseconds) specifying the amount of time to wait before executing the debounced function.
1
const debounce = (fn, delay = 300) => {};
  • timer Variable Declaration: Inside the debounce function, a let variable timer is declared to store the ID of the timeout set by setTimeout.
1
let timer;
  • Inner Function Definition: An anonymous arrow function is defined to serve as the debounced version of the input function fn. This function accepts any number of arguments through the rest parameter …args.
1
return function (...args) {};
  • Clearing Previous Timeout: When the inner function is called, the first thing it does is clear any previously set timeout using the timer variable and the clearTimeout function. This prevents the previous debounced function execution from happening.
1
clearTimeout(timer);
  • Setting New Timeout: A new timeout is set using setTimeout, which calls the original input function fn with the provided arguments …args after the specified delay. The timer variable stores the ID of the new timeout.
1
timer = setTimeout(() => {
2
fn(...args);
3
}, delay);

When calling tryIt multiple times within a short time span, only the last call will be executed after a 2000-millisecond delay, effectively demonstrating the debounce functionality.

7. Implement Throttling

Answer
1
const throttle = (fn, delay = 300) => {
2
let isWaiting = false;
3
return (...args) => {
4
if (!isWaiting) {
5
fn(...args);
6
isWaiting = true;
7
setTimeout(() => {
8
isWaiting = false;
9
}, delay);
10
}
11
};
12
};
13
14
const inputRes = (arg) => {
15
console.log(`The arg is ${arg}`);
16
};
17
18
const tryIt = throttle(inputRes, 2000); // Initial call
19
20
setTimeout(() => {
21
tryIt("LOL");
22
}, 1000); // ignored
23
24
setTimeout(() => {
25
tryIt("LOL");
26
}, 1500); // ignored
27
28
setTimeout(() => {
29
tryIt("LOL");
30
}, 2400); // Called

Explanation:

This JavaScript code demonstrates the concept of throttling, which is a technique used to control the execution rate of a function, ensuring that it is called no more than once within a specific time interval. This is often used to limit the rate at which expensive operations are performed, such as API calls or event handlers.

  • throttle Function: The throttle function is defined as a higher-order function that returns another function as its output. It takes two arguments: fn, which is the function to be throttled, and an optional delay argument (default value: 300 milliseconds) specifying the minimum time interval between function calls.
1
const throttle = (fn, delay = 300) => {};
  • isWaiting Variable Declaration: Inside the throttle function, a let variable isWaiting is declared to track whether the throttled function is currently in the “waiting” state.
1
let isWaiting = false;
  • Inner Function Definition: An arrow function is defined to serve as the throttled version of the input function fn. This function accepts any number of arguments through the rest parameter …args.
1
return (...args) => {};
  • Checking isWaiting Flag: Within the inner function, the code checks if the isWaiting flag is set to false. If not, it proceeds to execute the input function fn with the provided arguments …args.
1
if (!isWaiting) {
2
fn(...args);
3
}
  • Setting isWaiting Flag and Setting Timeout: After calling the input function, the code sets isWaiting to true to indicate that the function is now in the waiting state. Then, it uses setTimeout to reset the isWaiting flag to false after the specified delay, allowing the throttled function to be called again.
1
isWaiting = true;
2
setTimeout(() => {
3
isWaiting = false;
4
}, delay);

Throttling Demonstration: The code uses setTimeout to schedule calls to the throttled tryIt function with different arguments at different times. The first call happens immediately (tryIt(“LOL”);). The second and third calls are scheduled to happen after 1000 and 1500 milliseconds, respectively. Since these calls occur within the 2000-millisecond throttle delay, they are ignored. The fourth call, scheduled after 2400 milliseconds, is executed, demonstrating the throttling functionality.

1
setTimeout(() => {
2
tryIt("LOL");
3
}, 1000); // ignored
4
setTimeout(() => {
5
tryIt("LOL");
6
}, 1500); // ignored
7
setTimeout(() => {
8
tryIt("LOL");
9
}, 2400); // Called

In summary, the throttle function ensures that the input function fn is called at most once within the specified time interval delay, thereby controlling the rate of function execution.

Resources

CSS-Tricks: Debouncing and Throttling Explained Through Examples

David Walsh Blog: JavaScript Debounce Example

Medium: Understanding JavaScript Debounce

MDN Web Docs: Throttling

Educative: Understanding Debounce and Throttle Functions in JavaScript

Coding Ninjas: Understanding JavaScript Throttling by Building Your Own Throttle Function

8. Interacting with DOM

Task 1: Highlight all the words longer than 8 characters in the document.

Answer
1
const textP = document.querySelector("p");
2
3
textP.innerHTML = textP.innerHTML
4
.split(" ")
5
.map((word) =>
6
word.length > 8
7
? `<span style="background-color: yellow">${word}</span>`
8
: word
9
)
10
.join(" ");

Task 2: Add a link to the source after the paragraph element.

Answer
1
const link = document.createElement("a");
2
link.href =
3
"https://designtechworld.medium.com/everything-about-currying-in-javascript-a2614b82e6ca#:~:text=In%20conclusion%2C%20currying%20is%20a,reusability%2C%20composability%2C%20and%20flexibility.";
4
link.innerText = "Text for link";
5
6
document.body.appendChild(link);

Task 3: Split each new sentence to a separate line in the paragraph text. A sentence can be assumed to be a string of text terminated with a period (.)

Answer
1
textP.innerHTML =
2
textP.innerHTML.split(/\.|\!|\?[^.|<]/).join(".</p><p>") + "</p>";

Resources

MDN intro to the DOM

9. Implement a click on todo item as fast as possible

Answer
1
const toDoList = document
2
.querySelector(".todo-list")
3
.addEventListener("click", (e) => console.log(e.target.innerText));

Explanation:

Event delegation is a technique in JavaScript where an event listener is attached to a parent element rather than individual child elements. When an event occurs on a child element, it bubbles up through the DOM tree, and the parent element’s event listener handles the event. This approach improves performance by reducing the number of event listeners needed. In the provided code snippet, event delegation is used:

  • toDoList is assigned the value of the element with the class
  • .todo-list from the document.
  • An event listener is attached to the entire
  • .todo-list element, listening for any click events that occur within it or on any of its child elements.
  • When a click event occurs, the event object (e) is passed to the callback function, which then logs the innerText of the specific element that was clicked (e.target) to the console.

This code demonstrates event delegation because a single event listener is attached to the parent .todo-list element, and any click events on its child elements will bubble up to be handled by this single listener. This helps keep the code more efficient and maintainable compared to attaching individual event listeners to each child element.

Resources

JsInfo Event delegation

10. Implement XML HTTP Request

Answer
1
// Answer
2
const xhr = new XMLHttpRequest();
3
xhr.open("GET", "https://asafssaf.com");
4
xhr.send();
5
xhr.onload = function () {
6
if (xhr.status !== 200) {
7
console.log("Error" + xhr.status + xhr.tatusText);
8
} else {
9
console.log("Succes", xhr.response);
10
}
11
};
12
13
xhr.onerror = function () {
14
console.log("request failed");
15
};

Explanation:

XML HTTP requests are not used anymore (nowadays we use fetch() or 3rd party solutions like Axios), but this question may appear if you are being interviewed for postition which will include work wiht legacy codebases, so It’s good to know how this worked back in the days.

Summary

Here are 10 of most common JavaScript interview coding questions you can face in 2024. This is a series of interview preperation posts. So stay tuned! You can follow me on social media, where I’ll introduce new blog posts as soon as they are published on the website.

Avatar of Oleh Minko
Oleh Minko Web Developer

Related Articles:

If this was helpful, you can 'buy me a coffe' service logo - cup of coffee Buy me a coffee