Javascript Interview Questions 2024: Coding Interview - Part 1

In this post I will list some common JavaScript 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 into the answer

1. Basic JS methods

With a given array of users write the code to:

  • Get array of names of all users;
  • Get back only active users;
  • Sort users by age in descending order;
  • Log the answer to console;
1
// Array of users
2
const users = [
3
{
4
id: 1,
5
name: "Jack",
6
isActive: true,
7
age: 20,
8
},
9
{
10
id: 2,
11
name: "John",
12
isActive: true,
13
age: 18,
14
},
15
{
16
id: 3,
17
name: "Mike",
18
isActive: false,
19
age: 30,
20
},
21
];
Answer
1
// Answer
2
const neededUsers = users
3
.sort((user1, user2) => (user1.age < user2.age ? 1 : -1))
4
.filter((user) => user.isActive)
5
.map((user) => user.name);
6
7
console.log(neededUsers);

Explanation:

All wee need to do is use basic javascript methods:

  • .sort() : callback function takes two arguments - in our case user1 and user2 and compares them using ternay operator. If the result of our evaluation is true it returns 1 and if false -1. This way users are sorted in descending order.

  • .filter(): iterates over the array and returns a new array of users which have isActive = true;

  • .map(): maps over the array and applies a callback function to each item in array: in our case just returns a name of a user.

I chained all methods but it’s absolutely ok to write each one separately and refactor later.

Resources

MDN Map

MDN Filter

MDN Sort

2. Null vs Undefined

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

1
// Example 1
2
let var1;
3
console.log(var1);
4
console.log(typeof var1);
Answer
1
// Answer
2
undefined;
3
`undefined`;

Explanation:

Declared but anassigned variable in js has ‘undefiend’ value and ‘undefined’ type. (typeof operator returns operand`s type as a tring)

1
// Example 2
2
let var2 = null;
3
console.log(var2);
4
console.log(typeof var2);
Answer
1
// Answer
2
null;
3
[object]; // "object" (not "null" for legacy reasons)

Explanation:

Null and undefined in JS are both used to descirbe absence of a meaningfull value. Undefined usually used by JS engine, and null is used py programmer to explicitly show that variable doesn`t have any meaningfull value;

Resources

MDN Null

MDN Undefined

3. Hoisting

What will be console logged ?

1
//Q1
2
console.log(foo);
3
foo = 1;
Answer
1
// Answer
2
reference Error

Explanation:

“foo = 1” - is a undeclared variable . In strict mode it throws the reference error, in non-strict mode it is a global variable the same as var and will console log ‘undefined’.

1
//Q2
2
console.log(foo);
3
var foo = 2;
Answer
1
// Answer
2
Undefined;

Explanation:

var declaration of a variable in JS is hoisted to the top of the scope. But not it`s assigned value.

Resources

MDN Hoisting

FreeCodeCamp Post

4. Closure

Task: Create a counter function which has increment and getValue functionality.

Answer
1
// Answer
2
function privateCounter() {
3
let count = 0;
4
return {
5
increment: (value = 1) => {
6
count += value;
7
},
8
getValue: () => {
9
return count;
10
},
11
};
12
}
13
14
const counter = privateCounter();
15
16
console.log(counter.getValue());
17
counter.increment();
18
console.log(counter.getValue());

Explanation:

A closure is the combination of a function and a lexical environment within which that function was declared. Closures are functions that have access to the outer(enclosing) function’s variables, even after the outer function was returned.

In our solution access to the ‘count’ variable is only possible through counter methods, we cannot access it in any other way. It’s, so to say, ‘closed’ inside our counter function. Used in data privacy and more.

Resources

JsInfo Closure Article

MDN Closure

5. Currying

Task: Write a function which helps to achieve multiply(a)(b) and returns product of a and b.

Answer
1
// Answer
2
function multiply(a) {
3
return (b) => {
4
return a * b;
5
};
6
}
7
const val = multiply(2)(4);
8
console.log(val);

Explanation:

Currying is a technique in JavaScript that allows you to transform functions with multiple arguments into a sequence of functions, each taking one argument at a time. It promotes code reusability, composability, and flexibility

Resources

JsInfo Currying

FreeCodeCamp Post Currying

6. JS6

Task: Write a function which gets an array and an element and returns an array with this element in the end.

Answer
1
// Answer
2
const nums = [1, 2];
3
4
function moveToTheEnd(arr, el) {
5
const newArr = [...arr, el];
6
return newArr;
7
} // This is also called a pure function: a) returns same result with the same input; b) doesn`t modify any variables outside the function.
8
console.log(moveToTheEnd(nums, 9)); // [1, 2, 9]
9
console.log(nums); // [1,2]
10
11
// Also you can write it in one line using arrow function:
12
const addToTheEnd = (arr, el) => [...arr, el];

Explanation:

All we need to do is to use spread operator(…) which ‘spreads’ or destructures and makes a copy of the items in the array.

7. JS6

Task: Write a function which will concatenate 2 arrays.

Answer
1
const array1 = [1, 2];
2
const array2 = [3, 4];
3
4
// Answer 1: using spread operator
5
function concatArrs(arr1, arr2) {
6
return [...arr1, ...arr2];
7
}
8
9
// Answer 2: using concat method
10
function concatArrs2(arr1, arr2) {
11
return arr1.concat(arr2);
12
}
13
14
console.log(concatArrs(array1, array2));
15
console.log(concatArrs2(array1, array2));

Explanation:

Again we can solve this with spread operator or with .concat() method.

Resources

JsInfo Spread and Rest syntax

MDN Spread syntax

8. Working with arrays 1

Task: Check that user with given name exists in array of objects.

Given Array
1
// Name to find: Mike
2
const users = [
3
{
4
id: 1,
5
name: "Jack",
6
isActive: true,
7
age: 20,
8
},
9
{
10
id: 2,
11
name: "John",
12
isActive: true,
13
age: 18,
14
},
15
{
16
id: 3,
17
name: "Mike",
18
isActive: false,
19
age: 30,
20
},
21
];
Answer
1
const users = [
2
{
3
id: 1,
4
name: "Jack",
5
isActive: true,
6
age: 20,
7
},
8
{
9
id: 2,
10
name: "John",
11
isActive: true,
12
age: 18,
13
},
14
{
15
id: 3,
16
name: "Mike",
17
isActive: false,
18
age: 30,
19
},
20
];
21
22
// Answer 1: usign for-of loop
23
const findName = (userName, users) => {
24
let exists = false;
25
for (let user of users) {
26
if (user.name === userName) exists = true;
27
}
28
return exists;
29
};
30
31
console.log(findName("Mike", users));
32
33
// Answer 2: using .some() method
34
const isNameExists = (userName, arr) =>
35
arr.some((user) => user.name.toLowerCase() === userName.toLowerCase());
36
console.log(isNameExists("Kike", users));
37
38
// Answer 3: using findIndex
39
const isNameExists2 = (userName, arr) => {
40
// If not found, .findIndex() will return -1
41
const index = arr.findIndex((user) => user.name === userName);
42
43
return index >= 0;
44
};

Explanation:

Here we have three different ways(and probably more) to solve this. Any of those will do the job, just pick up the one that you like and understand and use it.

  • for…of loop: declaring the variable ‘exists’ with boolean value type, mapping over the array and comparing each user’s name property with userName we need. If found - sets the exists to true and end the loop.

  • .some() method: probably fits the best for this task, maps over the array and looks for what we need. Returns true/false;

  • findIndex() method: maps over users in array, comparing the userName to name property, if found - returns the index of the item, if not - returns -1;

Resources

MDN for…of loop

MDN .findindex()

MDN .Some()

9. Working with arrays 2

Task: Remove all duplicates in the array.

given array
1
const array = [1, 2, 2, 3, 4, 5, 5, 5, 6, 7];
Answer
1
const array = [1, 2, 2, 3, 4, 5, 5, 5, 6, 7];
2
//Answer 1: using new Set(arr)
3
const uniqueArr = (arr) => {
4
return [...new Set(arr)];
5
};
6
console.log(uniqueArr(array));
7
8
//Answer 2: ForEach loop
9
const uniqueArr2 = (arr) => {
10
const res = [];
11
arr.forEach((item) => {
12
if (!res.includes(item)) {
13
res.push(item);
14
}
15
});
16
return res;
17
};
18
19
//Answer 3: .reduce()
20
const uniqueArr3 = (arr) => {
21
return arr.reduce((acc, el) => {
22
return acc.includes(el) ? acc : [...acc, el];
23
}, []);
24
};

Explanation:

The solutions:

  • Set(): it’s like an array but lets you only store the uniqe values of any type;
  • For each loop: looping over the array, checking if our result includes() the current item and if not pushing that item into our result.
  • .reduce(): takes a callback function with two arguments - accumulator, element and initial value for accumulator (in our case - empty array); it ierates over the array, checks if our accumulator includes already the item and if not - adds it to our accumulator with spread operator. Not the easiest solution, but anyway. I don’t reccomend to use it unless you will forget every other solution. Always go with a simplest solution first.

Resources

MDN Set

MDN .forEach

MDN .reduce()

10. Working with arrays 3

Task 1: Sort the array of numbers.

1
const array = [2, 10, 19, -12, 32, 11, 29, -91];
Answer
1
// Answer
2
const array = [2, 10, 19, -12, 32, 11, 29, -91];
3
4
// Mutating the origial array
5
console.log(array.sort((a, b) => a - b));
6
7
// Without mutating
8
const newSortedArray = array.toSorted((a, b) => a - b);
9
console.log(newSortedArray);

Explanation:

array.sort((a, b) => a - b) sorts the array using a comparison function. In this case, the comparison function subtracts b from a.

  • If the result of a - b is negative, it means a is less than b, so a should be placed before b.
  • If the result is positive, it means a is greater than b, so a should be placed after b.
  • If the result is zero, it means a and b are equal, so their relative order doesn’t change. .sort() is sorting the array ‘in place’, so mutatin the original.

array.toSorted() works the same pretty much, but makes a copy of array, without mutating the original. Added in 2023, safe to use in modern browsers already.

Task 2: Sort array of objects by athors last name.

1
const books = [
2
{ name: "Harry Potter", author: "Joanne Rowling" },
3
{ name: "Warcross", author: "Marie Lu" },
4
{ name: "The Hunger Games", author: "Suzanne Collins" },
5
];
Answer
1
// Answer
2
const books = [
3
{ name: "Harry Potter", author: "Joanne Rowling" },
4
{ name: "Warcross", author: "Marie Lu" },
5
{ name: "The Hunger Games", author: "Suzanne Collins" },
6
];
7
8
books.sort((book1, book2) => {
9
const authorLastName1 = book1.author.split(" ")[1];
10
11
const authorLastName2 = book2.author.split(" ")[1];
12
13
return authorLastName1 < authorLastName2 ? -1 : 1;
14
});
15
console.log(books);

Explanation:

Solution: splitting the fullName to get last name of the author; If authorLastName1 is lexicographically less than authorLastName2, it returns -1, otherwise it returns 1, indicating that book2 should come before book1 in the sorted array.

Resources

MDN .sort()

MDN .toSorted()

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