Frequently asked - JavaScript Interview Questions and Answers - Part 03
August 25, 202410 min read

Frequently asked - JavaScript Interview Questions and Answers - Part 03

JavaScriptInterview QuestionFrequently asked
share this article on

41. What is higher-order functions in JavaScript? Explain in details.

Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.

In JavaScript, functions are first-class objects. This means we can pass the functions to other functions as parameters, we can assign them to a variable or we can return a function from inside a function. For example, we can refer many array methods, which can accept a function as an argument.

var fruits = ['Apple', 'Banana', 'Mango', 'Orange'];
fruits.forEach(function(item, index, arr)
console.log('I love ' + item);
});
var numbers = [1, 2, 3];
var doubles = numbers.map(function(num)
return num * 2; });
//doubles is now [2, 4, 6] and numbers is still [1, 2, 3]

42. What are map, filter and reduce in JavaScript? Explain some of the methods to manipulate an array?

map is like a for loop, and it will transform the input values. Example,

var numbers = [1, 2, 3];
var doubles = numbers.map(function(num)
return num * 2; });
//doubles is now [2, 4, 6] and numbers is still [1, 2, 3]

reduce, as the name suggests, will reduce an array to single value, for example, calculating the sum of the array elements. The first parameter is a value which will be considered as an accumulator. The code is,

var numbers = [1, 2, 3];
var sum = numbers.reduce(function(accumulator, num)
return accumulator + num;  0);
//sum is 6 and the accumulator is 0.

filter, method will create an array containing all the elements that satisfied the condition. The code is,

var numbers = [1, 2, 3, 4];
var filtered = numbers.filter(function(num)
return num % 2 === 0; });
//filtered is [2, 4].

43. How do manipulate Canvas in JavaScript? How do you draw something on HTML5 Canvas?

Canvas is a new HTML5 DOM element that provides API for drawing shapes onto the space. First we need to place our <canvas> in our HTML5 and manipulate it by our JavaScript.

<canvas width="600" height="400" id="canvas">Canvas not supported</canvas>

The text inside the <canvas> will be shown only in the old browsers where HTML5 not supported. Now in JavaScript,

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle = "red";
context.fillRect(10, 10, 100, 50);

A new canvas is empty, meaning it is entirely transparent and thus shows up simply as empty space in the document.

The <canvas> tag is intended to support different styles of drawing. To get access to an actual drawing interface, we first need to create a context, which is an object whose methods provide the drawing interface. There are currently two widely supported drawing styles: “2d” for two-dimensional graphics and “webGL” for three-dimensional graphics through the OpenGL interface. After creating the context object, the example draws a red rectangle 100 pixels wide and 50 pixels high, with its top-left corner at coordinates (10, 10).

44. How do you draw an arc and rectangle in Canvas? What are all the shapes we can draw on Canvas?

Canvas offers rectangle, arc, path or line and curve shapes. To draw a rectangle:

var cx = document.querySelector("canvas").getContext("2d");
cx.strokeStyle = "blue";
cx.lineWidth = 5;
cx.strokeRect(5, 5, 50, 50);

To draw an circle we could use arc method. It takes six arguments. The first two is x and y co-ordinates, third is the radius of the circle, fourth and fifth parameters are start and end angle. And the last is a boolean value of drawing the circle in clockwise or anti-clockwise.

var ctx = document.getElementById("canvas").getContext("2d");
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();

Canvas also provides quadraticCurveTo and arcTo to draw curved lines.

45. What is ECMAScript 6? What are the new features?

ECMAScript was created to standardize JavaScript. The latest standardized JavaScript version is called ECMAScript 6 also known as ECMAScript 2015.

ES6 includes the following new features:

46. What is arrow function in ECMAScript 6?

Arrow function is shorthand syntax for a function using =>. Unlike functions, arrows share the same lexical this as their surrounding code.

var odds = [1, 2, 3, 4, 5].map(v => v % 2 != 0);

An arrow function does not create its own this context, so this has its original meaning from the enclosing context. Thus, the following code works as expected:

function Person()
  this.age = 0;
 setInterval(() => 
    this.age++; // |this| properly refers to the person object
   1000);
}
var p = new Person();

47. What is Polymorphism? How do you use it in JavaScript? Explain with examples.

Polymorphism is the practice of designing objects to share behaviors and to be able to override shared behaviors with specific ones. Polymorphism takes advantage of inheritance in order to make this happen. Consider the below Person class:

function Person(name, age)
  this.name = name;
  this.age = age;
}

We are now adding a method that could be shared.

Person.prototype.getInfo = function()
  return "I am " + this.name + " and " +  this.age + " years old.";
};

Next we wish to have a subclass of Person, called Employee

function Employee(name, age, salary)
  this.nane = name;
  this.age = age;
  this.salary = salary;
}
Employee.prototype = new Person();

Now we want to override the getInfo method in the Employee subclass. Because, we want to display more information about the class.

Employee.prototype.getInfo = function()
  return "I am " + this.name + " " +  this.age + " years old and earns " + this.salary;
};

These can be used similar to your original code use,

var person = new Person('John', 26);
var employee = new Employee('Doe', 28, 50000);
console.log(person.getInfo());
console.log(employee.getInfo());

This is not the classic Polymorphism that we can see in statically-typed languages, since JavaScript is dynamic-typed language. But the basic idea of Polymorphism is to share behaviors.

48. what is currying in JavaScript?

Currying means constructing a function that process with partial parameters and return a function which when invoked would accept remaining parameters and return the final output. A simple example is,

var greeting = function(greeting) 
  return function(name) 
    console.log(greeting + " "   + name + "!");
  };
};

When invoking it,

var greetHello = greeting( "Hello" );
greetHello( "World" ); // Hello World!
greeting( "Javascript" ); //Hello Javascript!

We can also call the function immediately,

greeting( "World" )( "World" ); // Hello World!

The greeting function accepts a single argument and returns a function and when this returned function invoked sooner or later, it can accepts the remaining name parameter and return the final output.

49. How do you generate a random numbers between given number?

JavaScript offers Math.random which generates a random floating point number between 0 to 1. Then we can round them of using Math.floor. The easy way to generate random number is:

Math.floor(Math.random() * (1 + Max - Min)) + Min

For example, if we want to generate a number between 1 to 6:

Math.floor(Math.random() * 6) + 1

50. What is NaN in Javascript?

NaN means Not-A-Number—the same as the value of Number.NaN. Several operations can lead to NaN result. Some of them are,

2 / 'a';
Math.sqrt(-2)
Math.log(-1)
0/0
parseFloat('foo')

The typeof NaN returns number. And comparing NaN with NaN yields false.

NaN === NaN // false

To check NaN, we could use isNaN(NaN) function, or in ECMAScript 6 Number.isNaN(NaN)

51. What is Ajax?

AJAX stands for Asynchronous JavaScript And XML. AJAX’s most appealing characteristic is its “asynchronous” nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.

The two major features of AJAX allow you to do the following:

52. How do you make an http request in Ajax?

In order to make an HTTP request to the server, we need an object called XMLHttpRequest. In older version of IE we can still use this feature as as an ActiveX object called XMLHTTP.

var xhr;
if (window.XMLHttpRequest) 
  xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) 
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

After instantiate this, we need to assign a callback function to xhr.onreadystatechange to tell the XMLHttp request object to handle the response.

httpRequest.onreadystatechange = function()
//Check the request is completed
  if (httpRequest.readyState === 4)     //Check if the request is success
    if (httpRequest.status === 200)       alert(httpRequest.responseText);
    } else 
      //request failure
    }
  }
};

Now we are ready to send the request to the server.

httpRequest.open('GET', 'http://www.example.org/some.file', true);
httpRequest.send();

53. What are all the readyState values in XMLHTTPRequest.readyState?

This value indicates where the server is in its processing. They are as follows:

Since there are five state for the request, our callback function will be executed everytime the state changes from 0 to 5. This is the reason we need to check the readyState value to 4 to check if the server is completly done with our request.

54. What is <noscript>?

The HTML <noscript> element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser.

<noscript>
<!-- anchor linking to external file -->
<a href="https://www.noscript.com/">Web page for noscript browser</a>
</noscript>
<p>We are good to go!</p>

The <noscript> element can be used in both <head> and <body>.

When used inside the <head> element: <noscript> must contain only <link>, <style>, and <meta> elements.

55. What is Call Stack in JavaScript?

JavaScript’s functions forms a stack of frames. These are called Call Stack.

function foo(b) 
  var a = 10;
  return a + b + 11;
}
function bar(x) 
  var y = 3;
  return foo(x * y);
}
console.log(bar(7));

When we call bar, the first frame is created in the Call Stack with the functions arguments and local variables. The bar function calls foo from itself, which will create another frame and pushed to the top of the Call Stack. This stack also contains the foo’s arguments and local variables. When foo returns a value or complete execution, it is removed from the Stack and when bar returns the Stack is empty.

56. What is Run-to-Completion?

In JavaScript, Each line is processed completely before any other line is processed. And whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). This is called Run-to-Completion.


  1. Javasript Interview question and answers - Part 01
  2. Javasript Interview question and answers - Part 02
Back to Articles