JavaScript Interview Questions: Arrays

Manu Bhardwaj
codeburst
Published in
2 min readOct 2, 2020

--

JavaScript has been the most used programming language for many years now, yet people continue to find it hard to get a grasp of. This article will discuss some of the most frequently asked questions in JavaScript.

Question

What is the output of the following code?

const arrayOfOddNumbers = [1, 3, 5];
arrayOfOddNumbers[100] = 199;
console.log(arrayOfOddNumbers.length);

Solution

101

The reason for this solution is as follows: JavaScript placesempty as a value for indices 3 - 99. Thus, when you set the value of the 100th index, the array looks like:

And you get the length as 101.

Question

How can you double elements of an array using reduce? Please note that you cannot create additional variables.

Solution

const arrayOfNumbers = [1, 2, 3, 4];arrayOfNumbers.reduce((accumulator, currentValue, index, array) => array[index] = array[index] * 2);

Question

What is the output of the following code snippet?

let arrayOfLetters = ['a','b','c','d','e','f'];
const anotherArrayOfLetters = arrayOfLetters;
arrayOfLetters = [];
console.log(anotherArrayOfLetters);

Solution

['a','b','c','d','e','f']

When we carry out the above (containing arrayOfLetters = []) you create a new array and break the old reference. Thus, anotherArrayOfLetters has no effect on it since it is still pointing to the old array.

Question

How could you print unique values from an array?

const arrOfNum = [1, 2, 2, 4, 5, 6, 6];
console.log(getUniqueValues(arrOfNum)); // [1, 2, 4, 5, 6]

Solution

function getUniqueValues(arrOfNum) {
const set = new Set(arrOfNum);
return [...set];
}

A value in the Set may only occur once; it is unique in the Set's collection.

Question

How could you destructure array elements?

Solution

Without destructuring:

const address = ["583, Margaret Street", "LOS ANGELES, CA", "USA"];console.log(
"Address 1: " + address[0],
"Address 2: " + address[1],
"Address 3: " + address[2]
);

With destructuring:

const [address1, address2, address3] = ["583, Margaret Street", "LOS ANGELES, CA", "USA"];console.log(
"Address 1: " + address1,
"Address 2: " + address2,
"Address 3: " + address3
);

Wrapping up

In my personal opinion, JavaScript isn’t the most complicated language, however it is a language with a lot of depth. If we can construct a clear understanding of the topics that we regularly use then it becomes extremely easy for us to get a better understanding of the nuances of JaveScript.

Did you enjoy this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!

--

--