JavaScript Coding Questions for Interview.

Click here to know why (0.1 + 0.2 === 0.3) is not equal to True.

JavaScript Coding Questions for Interview.

Journey to become a self learner Full Stack Developer!

1) Explain what is a callback function, with an example.

Answer: A function that is passed as an argument to another function is called as callback function. This callback function will be executed after some operation has been completed.
Code:


2) Reverse each word of a given string.

Example:
Given string - Welcome to Hello World
Should become - emocleW ot olleH dlroW

Code:


3) Write some code to check if an object is an array or not.

Answer:

Array.isArray(object) tells if an object is an array or not.
Array.isArray is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5

Code:


4) How to empty an array in JavaScript?

Given Array –>  arrayList =  ['a', 'b', 'c', 'd', 'e', 'f'];

Answer-1:

arrayList = [];

The above approach is good when we have not referenced this array to another variable.

Problem in Answer-1:

Answer-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.

Answer-3:

arrayList.splice(0, arrayList.length);

This way of emptying an array will also works same as Answer-2, this will also empty all references.

Answer-4:

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

This way of emptying an array will also works same as Answer-2, this will also empty all references. But this approach not recommended as it runs in loop.


5) 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 we divide by 1.


6) Solve this Problem:

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

Code:

To create a function named duplicate() which should take an array as an argument and returns a duplicate array.


7) Write a 'mul' function which should invoke as below syntax.

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

Code:

function mul (x) {
  return function (y) { // anonymous function
    return function (z) { // anonymous function
      return x * y * z;
    };
  };
}

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 three arguments which is being passed in successive order.


8) What is Closure in JavaScript? Write an example code.

Answer: A closure is a function defined inside another function. A closure function is an inner function and parent function is an outer function. Also a closure function have access to the variables which are defined in parent function scope, since closure function is inside parent function.

The closure function has access to variable in three scopes:

  • Variable declared in its own scope
  • Variable declared in parent function scope
  • Variable declared in global namespace

Explanation: innerFunction is closure function which is defined inside outerFunction and has access to all variables which is declared and defined in outerFunction scope. Also, closure function has access to variable which is declared in global namespace.

Output of above code will be:

"outerArg = 4
outerFuncVar = x
innerArg = 3
innerFuncVar = y
globalVar = abc"

9) Solve this Problem:

var addSeven = createBase(7);
addSeven(10); // output : 17
addSeven(21); // output : 28

Code:

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 is 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(7);
console.log(addSix(10)); // output : 17
console.log(addSix(21)); // output : 28

10) FizzBuzz Challenge

Write 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.

Code:


11) Given two strings, return true if they are anagrams of one another.

For example: Mary is an anagram of Army

Code:


12) Use a closure to create a private counter.

Answer: A closure – is when we create a function within an outer function.
A closure allows us to update a private variable but the variable shouldn't be accessible from outside the function without the use of a helper function.

Code:


13) List of false values and true values, which are coercion to a Boolean.

Answer:

List of 'false' values:

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

List of 'true' values:

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

14) Solve this Problem:

Code:

(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.


15) Solve this Problem:

multiply(5)(6);

Answer:

We need to create a closure function, the inner function is to be created within outer function, and the inner function will have access to a variable a from outer function.

// outer function
function multiply(a) {
  // inner function
  return function(b) {
    return a * b;
  }
}

console.log(multiply(4)(5)); // Output: 20

16. Write code to explain this keyword?

Answer:

In JavaScript this always refers to the 'owner' of the function or to the object that a function is calling.

Example Code:


17. How to 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.

Example Code:

function func() {
  // private variable, allowed to access within the function func()
  var priv = "I am a private variable";
}

console.log(priv); // throws an error: priv is not defined 

To access the value of private variable, a helper function is required which returns the value of private variable.

function func() {
  // private variable, allowed to access within the function func()
  var priv = "I am a private variable";
  
  // this will return a function, and this function will return 
  // a value of priv variable
  return function() {
    return priv;
  }
}

// call a function func
var funcRef = func();
// now, call a function inside a funcRef
console.log(funcRef()); // Output: "I am a private variable"

Another Example:

function func2() {
  var priv = "I am a private variable";
  // this function itself returns a value of priv variable
  return priv;
}

console.log(func2()); // Output: "I am a private variable"

18) Explain the Output of following code:

var output = (function(x) {
  delete x;
  return x;
})(0);

console.log(output);

Answer: Output of above code will be 0.
because delete operator is used to delete a property from an object. Here x is not a property of an object it's local variable. delete operator doesn't affect local variables.


19) Explain the Output of following code:

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

Answer: Output of above code will be abc.
because emp1 object got company as prototype property. delete operator doesn't delete prototype property. emp1 object doesn't have company as its own property. We can test it like this:

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.


20) Why (0.1 + 0.2 === 0.3) is not equal to True?

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.

// this is what not expecting!
x = 0.1 + 0.2
0.30000000000000004

// this will solve our problem
y = Math.round(x * 100) / 100
0.3

21) When to use the bind function?

Answer: The bind() method creates a new function that has its this keyword which is set to the provided value we provide to the new function.

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.

Example Code: