Javascript — Tricky Questions-Array

Eishta Mittal
2 min readMay 23, 2022
  1. Write an example of a pure and impure function to add a value to an array
// Impure Examplelet arr = [];
const impureAddition = (num) => arr.push(num);
impureAddition(10);
// Pure Exampleconst pureAddition = (num) => (newArr) => [...newArr, num];
pureAddition(10)([]);

2. What will be the output of the below code?

console.log(['a']+['b']);

Answer: ‘ab’

3. What will be the output of the below code?

console.log([1, 3, 4, 2]["sort"]());

Answer: [1,2,3,4]

4. What will be the output of the below code?

console.log([1, 3, 4, 2]["sort"]["constructor"](alert("Boom")));

Answer: Alerts Boom

5. What will be the output of the below code?

const clothes = ['jacket', 't-shirt'];
clothes.length = 0;
clothes[0]; // => ???

Answer:
undefined
clothes.length = 0; deletes the array and hence clothes[0] does not exist

6. What will be the output of the below code?

const length = 4;
const numbers = [];
for (var i = 0; i < length; i++);{
numbers.push(i + 1);
}
numbers;

Answer: [5]
Why ? => there is semicolon after the for loop and before the executing block and var makes i global . So i can be accessed after the loop ends with a value 4.

7. What will be the output of the below code?

const length = 4;
const numbers = [];
for (let j = 0; j < length; j++);{
numbers.push(j + 1); // reference error
}
console.log(j); // reference error
numbers;

Answer: here let does not create a global variable and hence gives an error

8. How to empty an array in JavaScript?

var list =  ['a', 'b', 'c', 'd', 'e', 'f'];
-> list.length = 0
-> list = []
-> arrayList.splice(0, arrayList.length);

9. What will be the output of the below code?

var arr1 = "john".split('');
var arr2 = arr1.reverse(); // returns the ref to arr1 only
var arr3 = "jones".split('');
arr2.push(arr3);

console.log("array 1: length=" + arr1.length + " last=" + arr1.slice(-1));

console.log("array 2: length=" + arr2.length + " last=" + arr2.slice(-1));

Answer:
“array 1: length=5 last=j,o,n,e,s”
“array 2: length=5 last=j,o,n,e,s”

Because both arr1 and arr2 refer to the same array as the reverse method on array returns the same array and not a new array.

--

--