JavaScript Coding Interview Question

1. How to check if an object is an array or not?

Mahadiul Hasan
13 min readNov 10, 2020

Answer: The best way to find whether an object is an instance of a particular class or not using toString method from Object.prototype

var arrayList = [1 , 2, 3];

One of the best use cases of type checking of an object is when we do method overloading in JavaScript. For understanding, these let's say we have a method called greet which take one single string and also a list of string, so making our greet method workable in both situations we need to know what kind of parameter is being passed, is it a single value or list of value?

function greet(param) {
if() {
// here have to check whether param is array or not
}
else {
}
}

However, in the above implementation it might not necessary to check type for an array, we can check for single value string and put array logic code in else block, let see the below code for the same.

function greet(param) {
if(typeof param === 'string') {
}
else {
// If param is of type array then this block of code would execute
}
}

Now it’s fine we can go with the above two implementations, but when we have a situation like a parameter can be single value, array, and object type then we will be in trouble.

Coming back to checking the type of object, As we mentioned that we can use Object.prototype.toString

if(Object.prototype.toString.call(arrayList) === '[object Array]') {
console.log('Array!');
}

If you are using jQuery then you can also use jQuery isArray method:

if($.isArray(arrayList)) {
console.log('Array');
} else {
console.log('Not an array');
}

FYI jQuery uses Object.prototype.toString.call internally to check whether an object is an array or not.

In a modern browser, you can also use:

Array.isArray(arrayList);

Array.isArray is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5, and Safari 5

2. How to empty an array in JavaScript?

var arrayList =  ['a', 'b', 'c', 'd', 'e', 'f'];

Answer: Method 1

arrayList = [];

The above code will set the variable arrayList to a new empty array. This is recommended if you don't have references to the original array arrayList anywhere else because It will actually create a new empty array. You should be careful with this way of empty the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged, Only use this way if you have only referenced the array by its original variable arrayList.

For Instance:

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var anotherArrayList = arrayList; // Referenced arrayList by another variable
arrayList = []; // Empty the array
console.log(anotherArrayList); // Output ['a', 'b', 'c', 'd', 'e', 'f']

Method 2

arrayList.length = 0;

The above code will clear the existing array by setting its length to 0. This way of empty the array also updates all the reference variable which points to the original array. This way of empty the array is useful when you want to update all another reference variable which pointing to arrayList.

For Instance:

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var anotherArrayList = arrayList; // Referenced arrayList by another variable
arrayList.length = 0; // Empty the array by setting length to 0
console.log(anotherArrayList); // Output []

Method 3

arrayList.splice(0, arrayList.length);

The above implementation will also work perfectly. This way of empty the array will also update all the references of the original array.

var arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var anotherArrayList = arrayList; // Referenced arrayList by another variable
arrayList.splice(0, arrayList.length); // Empty the array by setting length to 0
console.log(anotherArrayList); // Output []

Method 4

while(arrayList.length) {
arrayList.pop();
}

The above implementation can also empty the array. But not recommended to use often.

3. How would you verify a prime number?

Answer: a prime number is only divisible by itself and 1. So, I will run a while loop and increase by 1. (look at the code example. If you don’t get it. this is not your cake. do learn javaScript basics and come back.

function isPrime(n){
var divisor = 2;
while (n> divisor){
if(n % divisor == 0){
return false;
}else
divisor++;
}
return true;
}
>isPrime(137); //true
>isPrime(237); //false

Interviewer: Can you make this better?

You: yes. the divisor is increased 1 at a time. after 3 I can increase by 2. if a number is divisible by any even number, it will be divisible by 2.

4. How could you find all prime factors of a number?

Answer: Run a while loop. start dividing by two and if not divisible increase divider until u r done.

function primeFactors(n){
var factors = [],
divisor = 2;
while(n>2){
if(n % divisor == 0){
factors.push(divisor);
n= n/ divisor; }
else{
divisor++;
}
}
return factors;
}
> primeFactors(69); //[3, 23]

5. How do get nth Fibonacci number?

Answer: I create an array and start from iterate through.

Fibonacci series is one of the most popular interview questions for beginners. so, you have to learn this one.

function fibonacci(n){
if(n<=1)
return n;
else
return fibonacci(n-1) + fibonacci (n-2);
}
> fibonacci(12); //144

6. How would you find the greatest common divisor of two numbers?

function greatestCommonDivisor(a, b){
if(b == 0)
return a;
else
return greatestCommonDivisor(b, a%b);
}

7. How would you remove duplicate members from an array?

Answer: will start a while looping and keep an object/ associated array. If i find an element for the first time I will set its value as true (that will tell me element added once.). if I find an element in the existing object, I will not insert it into the return array.

function removeDuplicate(arr){
var exists ={},
outArr = [],
elm;
for(var i =0; i<arr.length; i++){
elm = arr[i];
if(!exists[elm]){
outArr.push(elm);
exists[elm] = true;
}
}
return outArr;
}
> removeDuplicate([1,3,3,3,1,5,6,7,8,1]); //[1, 3, 5, 6, 7, 8]

8. How would you merge two sorted arrays?

Answer: I will keep a pointer for each array and (read the code. and be careful about this one.

function mergeSortedArray(a, b){
var merged = [],
aElm = a[0],
bElm = b[0],
i = 1,
j = 1;
if(a.length ==0)
return b;
if(b.length ==0)
return a;
while(aElm || bElm){
if((aElm && !bElm) || aElm < bElm){
merged.push(aElm);
aElm = a[i++];
}
else {
merged.push(bElm);
bElm = b[j++];
}
}
return merged;
}
> mergeSortedArray([2,5,6,9], [1,2,3,29]); //[1, 2, 2, 3, 5, 6, 9, 29]

9. How would you swap two numbers without using a temporary variable?

Answer: Waste time about thinking it. though u know the answer, act like you are thinking, and take your time to answer this one.

function swapNumb(a, b){
console.log('before swap: ','a: ', a, 'b: ', b);
b = b - a;
a = a + b;
b = a - b;
console.log('after swap: ','a: ', a, 'b: ', b);
}
> swapNumb(2, 3);
//before swap: a:2 b:3 //after swap: a:3 b:2

10. How would you reverse a string in JavaScript?

Answer: I can loop through the string and concatenate letters to a new string

function reverse(str){
if(!str || str.length <2) return str;
return str.split('').reverse().join('');
}

Question: Can you make reverse function as a string extension?

Answer: I need to add this function to the String.prototype and instead of using str as a parameter, I need to use this

String.prototype.reverse = function (){
if(!this || this.length <2) return this;
return this.split('').reverse().join('');
}
> 'abc'.reverse(); //'cba'

11. How would you reverse words in a sentence?

Answer: You have to check for white space and walk through the string. Ask if there could be multiple whitespaces.

function reverseWords(str){
return str.split(' ').reverse();
}

12. If you have a string like “I am the good boy”. How can you generate “I ma eht doog yob”? Please note that the words are in place but reverse.

Answer: To do this, I have to do both string reverse and word reverse.

function reverseInPlace(str){
return str.split(' ').reverse().join(' ').split('').reverse().join('');
}
> reverseInPlace('I am the good boy'); //"I ma eht doog yob"

13. How could you find the first non-repeating char in a string?

Answer: You must ask to follow up on questions.

Clarification: Is it case sensitive?

Interviewer: interviewer might say no.

Clarification: is it a very long string or a couple hundred?

Interviewer: Why does that matter

you: for example, if it is a very long string say a million characters, and I want to check whether 26 English characters are repeating. I might check whether all characters are duplicated in every 200 letters (for example) other than looping through the whole string. this will save computation time.

Interviewer: For simplicity, your string is “the quick brown fox jumps then quickly blow air”

Clarification: (silly question) ASCII or Unicode.

function firstNonRepeatChar(str){
var len = str.length,
char,
charCount = {};
for(var i =0; i<len; i++){
char = str[i];
if(charCount[char]){
charCount[char]++;
}
else
charCount[char] = 1;
}
for (var j in charCount){
if (charCount[j]==1)
return j;
}
}
>firstNonRepeatChar('the quick brown fox jumps then quickly blow air'); // "f"

14. How will you remove duplicate characters from a string?

You: This is very similar to the first non-repeating char. You will ask a similar question. Is it case sensitive?

If the interviewer says, this is case sensitive then life becomes easier for you. If he says no. you can either use string.toLowercase() to make the whole string lower. he might not like it. because the return string will not possess the same case. So

function removeDuplicateChar(str){
var len = str.length,
char,
charCount = {},
newStr = [];
for(var i =0; i<len; i++){
char = str[i];
if(charCount[char]){
charCount[char]++;
}
else
charCount[char] = 1;
}
for (var j in charCount){
if (charCount[j]==1)
newStr.push(j);
}
return newStr.join('');
}
> removeDuplicateChar('Learn more javascript dude'); //"Lnmojvsciptu"

15. How will you verify a word as a palindrome?

Answer: if you reverse a word and it becomes the same as the previous word, it is called a palindrome.

function checkPalindrom(str) {
return str == str.split('').reverse().join('');
}

16. If you have a function that generates a random number between 1 to 5 how could u generate random numbers 1 to 7 by using that function?

Answer: Very simple. think of some basic arithmetic and you will get it.

function rand5(){
return 1 + Math.random() * 4;
}
function rand7(){
return 5 + rand5() / 5 * 2;
}

17. from an unsorted array of numbers 1 to 100 excluding one number, how will you find that number?

Explanation: You have an array of numbers 1 to 100 in an array. Only one number is missing in the array. The array is unsorted. Find the missing number.

Answer: You have to act like you are thinking a lot. and then talk about the sum of a linear series of n numbers = n*(n+1)/2

function missingNumber(arr){
var n = arr.length+1,
sum = 0,
expectedSum = n* (n+1)/2;
for(var i = 0, len = arr.length; i < len; i++){
sum += arr[i];
}
return expectedSum - sum;
}
> missingNumber([5, 2, 6, 1, 3]); //4

18. From an unsorted array, check whether there are any two numbers that will sum up to a given number?

Answer: I can have an object where i will store the difference between sum and element. And then when i get to a new element and if i find the difference is the object, then i have a pair that sums up to the desired sum.

function sumFinder(arr, sum){
var differ = {},
len = arr.length,
substract;
for(var i =0; i<len; i++){
substract = sum - arr[i];
if(differ[substract])
return true;
else
differ[arr[i]] = true;
}
return false;
}
> sumFinder([6,4,3,2,1,7], 9); = true > sumFinder([6,4,3,2,1,7], 2); //false

19. How would you find the largest sum of any two elements?

Answer: This is actually very simple and straight forward. Just find the two largest number and return sum of them

function topSum(arr){
var biggest = arr[0],
second = arr[1],
len = arr.length,
i = 2;
if (len<2) return null;
if (biggest<second){
biggest = arr[1];
second = arr[0];
}
for(; i<len; i++){
if(arr[i] > biggest){
second = biggest;
biggest = arr[i];
}
else if (arr[i]>second){
second = arr[i];
}
}
return biggest + second;
}

20. Count the Total number of zeros from 1 upto n?

Answer: If n = 50. number of 0 would be 11 (0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100). Please note that 100 has two 0. This one looks simple but a little tricky

Explanation: So the trick here is. if you have a number 1 to 50 the value is 5. just 50 divided by 10. However, if the value is 100. the value is 11. you will get by 100/10 = 10 and 10/10. That's how you will get in the more zeros in one number like (100, 200, 1000)

function countZero(n){
var count = 0;
while(n>0){
count += Math.floor(n/10);
n = n/10;
}
return count;
}
> countZero(2014); // 223

21. How can you match the substring of a string?

Answer: Will use to pointer (one for string and another for the substring) while iterating the string. And will have another variable to hold the starting index of the initial match.

function subStringFinder(str, subStr){
var idx = 0,
i = 0,
j = 0,
len = str.length,
subLen = subStr.length;
for(; i<len; i++){
if(str[i] == subStr[j])
j++;
else
j = 0;
//check starting point or a match
if(j == 0)
idx = i;
else if (j == subLen)
return idx;
}
return -1;
}
> subStringFinder('abbcdabbbbbck', 'ab') // 0 > subStringFinder('abbcdabbbbbck', 'bck') // 9 //doesn't work for this one. > subStringFinder('abbcdabbbbbck', 'bbbck') // -1

22. How would you create all permutation of a string?

Answer: This could be a tough one based on your level of knowledge about an algorithm.

function permutations(str){
var arr = str.split(''),
len = arr.length,
perms = [],
rest,
picked,
restPerms,
next;
if (len == 0)
return [str];
for (var i=0; i<len; i++)
{
rest = Object.create(arr);
picked = rest.splice(i, 1);
restPerms = permutations(rest.join(''));
for (var j=0, jLen = restPerms.length; j< jLen; j++)
{
next = picked.concat(restPerms[j]);
perms.push(next.join(''));
}
}
return perms;
}

23. How would you use a closure to create a private counter?

Answer: You can create a function within an outer function (a closure) that allows you to update a private variable but the variable wouldn’t be accessible from outside the function without the use of a helper function.

function counter() {
var _counter = 0;
// return an object with several functions that allow you
// to modify the private _counter variable
return {
add: function(increment) { _counter += increment; },
retrieve: function() { return 'The counter is currently at: ' + _counter; }
}
}
// error if we try to access the private variable like below
// _counter;
// usage of our counter function
var c = counter();
c.add(5);
c.add(9);
// now we can access the private variable in the following way
c.retrieve(); // => The counter is currently at: 14

24. How does the “this” keyword work? Provide some code examples

Answer: In JavaScript, this always refers to the “owner” of the function we’re executing, or rather, to the object that a function is a method of.

Consider:

function foo() {
console.log( this.bar );
}
var bar = "global";var obj1 = {
bar: "obj1",
foo: foo
};
var obj2 = {
bar: "obj2"
};
foo(); // "global"
obj1.foo(); // "obj1"
foo.call( obj2 ); // "obj2"
new foo(); // undefined

25. What is “closure” in javascript? Provide an example?

Answer: A closure is a function defined inside another function (called parent function) and has access to the variable which is declared and defined in the parent function scope.

The closure has access to the variable in three scopes:

  • Variable declared in his own scope
  • Variable declared in parent function scope
  • Variable declared in the global namespace
var globalVar = "abc";// Parent self invoking function
(function outerFunction (outerArg) { // begin of scope outerFunction
// Variable declared in outerFunction function scope
var outerFuncVar = 'x';
// Closure self-invoking function
(function innerFunction (innerArg) { // begin of scope innerFunction
// variable declared in innerFunction function scope
var innerFuncVar = "y";
console.log(
"outerArg = " + outerArg + "\n" +
"outerFuncVar = " + outerFuncVar + "\n" +
"innerArg = " + innerArg + "\n" +
"innerFuncVar = " + innerFuncVar + "\n" +
"globalVar = " + globalVar);
// end of scope innerFunction
})(5); // Pass 5 as parameter
// end of scope outerFunction
})(7); // Pass 7 as parameter

innerFunction is a closure which is defined inside outerFunction and has access to all variable which is declared and defined in the outer function scope. In addition to this function defined inside the function as closure has access to a variable which is declared in global namespace.

The output of the above code would be:

outerArg = 7
outerFuncVar = x
innerArg = 5
innerFuncVar = y
globalVar = abc

26. When would you use the “bind” function?

Answer: The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Good use of the bind function is when you have a particular function that you want to call with a specific value. You can then use bind to pass a specific object to a function that uses a this reference.

function fullName() {
return "Hello, this is " + this.first + " " + this.last;
}
console.log(fullName()); // => Hello this is undefined undefined// create a person object and pass its values to the fullName function
var person = {first: "Foo", last: "Bar"};
console.log(fullName.bind(person)()); // => Hello this is Foo Bar

27. Write a function to check that a binary tree is a valid binary search tree.

Answer:

class BinaryTreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}

insertLeft(value) {
this.left = new BinaryTreeNode(value);
return this.left;
}

insertRight(value) {
this.right = new BinaryTreeNode(value);
return this.right;
}
}

28. What is the difference between declaring a function in the formats listed below?

var foo = function() {
// Some code
}
function bar () {
// Some code
}

Answer: The main difference is that function foo is defined at run-time and is called a function expression, whereas function bar is defined at parse time and is called a function statement. To understand it better, let's take a look at the code below :

// Run-Time function declaration
foo(); // Call foo function here, It will give an error
var foo = function() {
console.log("Hi I am inside Foo");
};
// Parse-Time function declaration
bar(); // Call bar function here, It will not give an Error
function bar() {
console.log("Hi I am inside Foo");
}

29. Provide some examples of non-boolean value coercion to a boolean one.

Answer: The question is when a non-boolean value is coerced to a boolean, does it become true or false, respectively?

The specific list of “falsy” values in JavaScript is as follows:

  • "" (empty string)
  • 0, -0, NaN (invalid number)
  • null, undefined
  • false

Any value that’s not on this “falsy” list is “truthy.” Here are some examples of those:

  • "hello"
  • 42
  • true
  • [ ], [ 1, "2", 3 ] (arrays)
  • { }, { a: 42 } (objects)
  • function foo() { .. } (functions)

30. What will be the output of the following code?

var y = 1;

if (function f() {}) {

y += typeof f;

}

console.log(y);

Answer: Above code would give output 1undefined. If condition statement evaluate using eval so eval(function f() {}) which return function f() {} which is true so inside if statement code executes. typeof f return undefined because if statement code executes at run time, so statement inside if condition evaluated at run time.

var k = 1;
if (1) {
eval(function foo() {});
k += typeof foo;
}
console.log(k);

The above code will also output 1undefined.

var k = 1;
if (1) {
function foo() {};
k += typeof foo;
}
console.log(k); // output 1function

--

--