JavaScript Coding Interview Questions

1
1444

Check that ultimate list of 25 advanced and tricky JavaScript Coding Interview Questions and Challenges to crack on your next senior web developer interview and got your next six-figure job offer in no time!

Q1: Given a string, reverse each word in the sentence?

For example Welcome to this Javascript Guide! should be become emocleW ot siht tpircsavaJ !ediuG

var string = "Welcome to this Javascript Guide!";

// Output becomes !ediuG tpircsavaJ siht ot emocleW
var reverseEntireSentence = reverseBySeparator(string, "");

// Output becomes emocleW ot siht tpircsavaJ !ediuG
var reverseEachWord = reverseBySeparator(reverseEntireSentence, " ");

function reverseBySeparator(string, separator) {
  return string.split(separator).reverse().join(separator);
}

Q2: Implement enqueue and dequeue using only two stacks

Enqueue means to add an element, dequeue to remove an element.

var inputStack = []; // First stack
var outputStack = []; // Second stack

// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
  return stackInput.push(item);
}

function dequeue(stackInput, stackOutput) {
  // Reverse the stack such that the first element of the output stack is the
  // last element of the input stack. After that, pop the top of the output to
  // get the first element that was ever pushed into the input stack
  if (stackOutput.length <= 0) {
    while(stackInput.length > 0) {
      var elementToOutput = stackInput.pop();
      stackOutput.push(elementToOutput);
    }
  }

  return stackOutput.pop();
}

Q3: Write a “mul” function which will properly when invoked as below syntax.

console.log(mul(2)(3)(4)); // output : 24
console.log(mul(4)(3)(4)); // output : 48

Here mul function accept the first argument and return anonymous function which take the second parameter and return anonymous function which take the third parameter and return multiplication of arguments which is being passed in successive

In JavaScript function defined inside has access to outer function variable and function is the first class object so it can be returned by function as well and passed as argument in another function.

  • A function is an instance of the Object type
  • A function can have properties and has a link back to its constructor method
  • Function can be stored as variable
  • Function can be pass as a parameter to another function
  • Function can be returned from function
function mul (x) {
  return function (y) { // anonymous function
    return function (z) { // anonymous function
      return x * y * z;
    };
  };
}

Q4: How to empty an array in JavaScript?

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

How could we empty the array above?

Method 1

arrayList = [];

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']arrayList.length = 0;

Method 2

arrayList.length = 0;

Above code will clear the existing array by setting its length to 0. This way of empty the array also update all the reference variable which pointing to the original array. This way of empty the array is useful when you want to update all the 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);

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();
}

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

Q5: How to check if an object is an array or not? Provide some code.

The best way to find whether an object is 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 this let 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 situation we need to know what kind of parameter is being passed, is it single value or list of value?

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

However, in above implementation it might not necessary to check type for array, we can check for single value string and put array logic code in else block, let see 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 above two implementations, but when we have a situation like a parameter can be single valuearray, and object type then we will be in trouble.

Coming back to checking 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 used 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 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

Q6: How would you use a closure to create a private counter?

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
Related Article: Learn more about JavaScript Sort

Q7: Write a function that would allow you to do this.

var addSix = createBase(6);
addSix(10); // returns 16
addSix(21); //

Answer:

You can create a closure to keep the value passed to the function createBase even after the inner function is returned. The inner function that is being returned is created within an outer function, making it a closure, and it has access to the variables within the outer function, in this case the variable baseNumber.

function createBase(baseNumber) {
  return function(N) {
    // we are referencing baseNumber here even though it was declared
    // outside of this function. Closures allow us to do this in JavaScript
    return baseNumber + N;
  }
}

var addSix = createBase(6);
addSix(10);
addSix(21);

Q8: How would you check if a number is an integer?

A very simply way to check if a number is a decimal or integer is to see if there is a remainder left when you divide by 1.

function isInt(num) {
  return num % 1 === 0;
}

console.log(isInt(4)); // true
console.log(isInt(12.2)); // false
console.log(isInt(0.3)); // false

Q9: Explain what a callback function is and provide a simple example.

callback function is a function that is passed to another function as an argument and is executed after some operation has been completed. Below is an example of a simple callback function that logs to the console after some operations have been completed.

function modifyArray(arr, callback) {
  // do something to arr here
  arr.push(100);
  // then execute the callback function that was passed
  callback();
}

var arr = [1, 2, 3, 4, 5];

modifyArray(arr, function() {
  console.log("array has been modified", arr);
});

Q10: FizzBuzz Challenge

Create a for loop that iterates up to 100 while outputting “fizz” at multiples of 3“buzz” at multiples of 5 and “fizzbuzz” at multiples of 3 and 5.

Answer:

Check out this version of FizzBuzz:

for (let i = 1; i <= 100; i++) {
  let f = i % 3 == 0,
    b = i % 5 == 0;
  console.log(f ? (b ? 'FizzBuzz' : 'Fizz') : b ? 'Buzz' : i);
}

Q11: Make this work

duplicate([1, 2, 3, 4, 5]); // [1,2,3,4,5,1,2,3,4,5]

Answer:

function duplicate(arr) {
  return arr.concat(arr);
}

duplicate([1, 2, 3, 4, 5]); // [1,2,3,4,5,1,2,3,4,5]

Q12: Provide some examples of non-bulean 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-0NaN (invalid number)
  • nullundefined
  • 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)

Q13: Given two strings, return true if they are anagrams of one another

For example: Mary is an anagram of Army

Answer:

var firstWord = "Mary";
var secondWord = "Army";

isAnagram(firstWord, secondWord); // true

function isAnagram(first, second) {
  // For case insensitivity, change both words to lowercase.
  var a = first.toLowerCase();
  var b = second.toLowerCase();

  // Sort the strings, and join the resulting array to a string. Compare the results
  a = a.split("").sort().join("");
  b = b.split("").sort().join("");

  return a === b;
}

Q14: 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 execute. typeof f return undefined because if statement code execute 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);

Above code will also output 1undefined.

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

Q15: What will the following code output?

(function() {
  var a = b = 5;
})();

console.log(b);

Answer:
The code above will output 5 even though it seems as if the variable was declared within a function and can’t be accessed outside of it. This is because

var a = b = 5;

is interpreted the following way:

var a = b;
b = 5;

But b is not declared anywhere in the function with var so it is set equal to 5 in the global scope.

Q16: Write a function that would allow you to do this

multiply(5)(6);

Answer:
You can create a closure to keep the value of a even after the inner function is returned. The inner function that is being returned is created within an outer function, making it a closure, and it has access to the variables within the outer function, in this case the variable a.

function multiply(a) {
  return function(b) {
    return a * b;
  }
}

multiply(5)(6);

Q17: 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
Python Interview Questions

Q18: Write a recursive function that performs a binary search

function recursiveBinarySearch(array, value, leftPosition, rightPosition) {
  // Value DNE
  if (leftPosition > rightPosition) return -1;

  var middlePivot = Math.floor((leftPosition + rightPosition) / 2);
  if (array[middlePivot] === value) {
    return middlePivot;
  } else if (array[middlePivot] > value) {
    return recursiveBinarySearch(array, value, leftPosition, middlePivot - 1);
  } else {
    return recursiveBinarySearch(array, value, middlePivot + 1, rightPosition);
  }
}

Q19: What is “closure” in javascript? Provide an example?

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

The closure has access to variable in three scopes:

  • Variable declared in his own scope
  • Variable declared in parent function scope
  • Variable declared in 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 closure which is defined inside outerFunction and has access to all variable which is declared and defined in outerFunction scope. In addition to this function defined inside function as closure has access to variable which is declared in global namespace.

Output of above code would be:

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

Q20: What will be the output of the following code?

var Employee = {
  company: 'xyz'
}
var emp1 = Object.create(Employee);
delete emp1.company
console.log(emp1.company);

Answer:
Above code will output xyz as output. Here emp1 object got company as prototype property. delete operator doesn’t delete prototype property.

emp1 object doesn’t have company as its own property. You can test it like:

console.log(emp1.hasOwnProperty('company')); //output : false

However, we can delete company property directly from Employee object using delete Employee.company or we can also delete from emp1 object using __proto__ property delete emp1.__proto__.company.

Q21: 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.

A good use of the bind function is when you have a particular function that you want to call with a specific this 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

Q22: What will the following code output?

0.1 + 0.2 === 0.3

Answer:
This will surprisingly output false because of floating point errors in internally representing certain numbers. 0.1 + 0.2 does not nicely come out to 0.3 but instead the result is actually 0.30000000000000004 because the computer cannot internally represent the correct number. One solution to get around this problem is to round the results when doing arithmetic with decimal numbers.

Q23: How would you create a private variable in JavaScript?

Answer:
To create a private variable in JavaScript that cannot be changed you need to create it as a local variable within a function. Even if the function is executed the variable cannot be accessed outside of the function. For example:

function func() {
  var priv = "secret code";
}

console.log(priv); // throws error

To access the variable, a helper function would need to be created that returns the private variable.

function func() {
  var priv = "secret code";
  return function() {
    return priv;
  }
}

var getPriv = func();
console.log(getPriv()); // => secret code

1 COMMENT