TOP 60 JavaScript Interview Questions (2020 Edition)[ Experienced Candidates]

Pratibha
15 min readNov 22, 2020
  1. What is hoisting and he will give one program and ask you for the output?
var x = 10;
function foo() {
console.log(x);
var x = 20;
console.log(x);
}
foo();
console.log(x);

Ans: Hoisting is a feature in JavaScript where the variable and function declaration will goes to the top of JavaScript execution context.

console.log(x); // Output -> undefined
var x = 10;
console.log(x); // Output -> 10

From an above example, the Engine execute it as below,

var x;
console.log(x);
x = 10;
console.log(x);

JavaScript declared variable will return undefined and it will print undefined and the it initialize with a value 10 and then it prints 10. This process is called hoisting.

From the example given below is compiled to,

var x = 10;
function foo() {
console.log(x);
var x = 20;
console.log(x);
}
foo();
console.log(x);

compiled to

var x; 
x = 10;
function foo() {
var x; // undefined
console.log(x); // Output -> undefined
x = 20;
console.log(x); // Output -> 20
}
foo()
console.log(x); // Output -> 10;

2. What is a Closure and explain with an example, and write a function to get mul(1)(2)(3);

Ans: Closure is a feature in JavaScript where the inner function can always have access to its outer function variable and its parameter after it get executed.

function mul(x) {
return function(y) {
return function(z) {
return x*y*z;
}
}
}let multiply = mul(1)(2)(3); // Output -> 6

3. What is prototype and why it’s used for? Define a custom function by which you can call as below,

var x = 'Hello AngularFeed';
x.upperCase(); // JavaScript defined function for uppercase.

Ans: Prototype is a JavaScript object which is used for inheritance in JavaScript. Every JavaScript Object has a prototype property in it where you can dynamically add or remove property to prototype object.

For eg,

String.prototype.toCamelCase = function(x) {
return x.upperCase();}
"get.name".toCamelCase();

4. What is IIFE function, it’s used and how do you pass a jQuery reference to it?

Ans: IIFE is a self invoked function which is also called immediately invoked function expression. The syntax to define IIFE is,

(function() { })(); 
<or>
(function() { }());

To pass parameter in IIFE then,

let result = (function(x) { 
return x;
}(10));
console.log(result); // -> 10

in the same way we could pass jQuery object to IIFE function,

let result = (function($) { 
return x;
}(jQuery));

Uses of IIFE,

a. It will invoked as soon as it is defined,

b. To avoid namespace collapse,

c. Create separate file as a module,

d. Used mostly for developing large application or modules.

5. What is the use of map, filter and reduce?

Ans: map, filter and reduce are the new methods introduce in ES 6 for array.

map: map will transform the array and return new array,

let array = [1,2,3,4,5];
let newArray = array.map((x)=> x+10)
console.log(array)// -> [1,2,3,4,5]
console.log(newArray); //-> [11,12,13,14,15]

filter: filter will also return a new array with a specific condition has passed,

let array = [1,2,3,4,5];
let newArray = array.filter((x)=> x > 3)
console.log(array)// -> [1,2,3,4,5]
console.log(newArray); //-> [4,5]

reduce: reduce will return a single value from an array,

let array = [1,2,3,4,5];
let newValue = array.reduce((acc, val, index, array)=> {
return acc + val
}, 0);console.log(array)// -> [1,2,3,4,5]
console.log(newValue); //-> 15

reduce take four arguments, they are accumulator, value, index and actual array, we can pass the initial value to an accumulator as we passed 0 to it.

6. How do you add item at array index 0?

Ans: To add item at index 0 in an array we can use unshift method,

let array = [1,2,3,4,5];
array.unshift(0);
console.log(array); //-> [0,1,2,3,4,5]

7. How many types of For loops in JavaScript and which you are using the most?

Ans: There are four type of For loops in JavaScript they are,

i. for loop

let array = [1,2,3,4,5];
for(let i = 0; i < array.length; i++) { console.log(array[i])}

ii. forEach()

let array = [1,2,3,4,5];
array.forEach((val, index) => console.log(val))

iii.for/of loop:

let array = [1,2,3,4,5];
for(let arr of array) { console.log(arr) }

iv. for/in loop:

let array = [1,2,3,4,5];
for(let arr in array) { console.log(array[arr])}

I usually prefer, for/of loop which returns direct value from an array.

8. What is the difference between normal function and arrow function?

Ans: The main difference between normal function and arrow function is that how the “this” scope will execute inside the function. The this keyword of a normal function will creates it’s own scope while in arrow function it refer the this object to its parent scope, if the parent scope is an object then it takes the reference of parent object this.

9. Write a Palindrome program with better approach?

var isPalindrome = function (string) {
if (string == string.split('').reverse().join('')) {
alert(string + ' is palindrome.');
}
else {
alert(string + ' is not palindrome.');
}
}

document.getElementById('form_id').onsubmit = function() {
isPalindrome(document.getElementById('your_input').value);
}

10. What is Event delegation? how do you stop it?

Capturing and bubbling allow us to implement one of most powerful event handling patterns called event delegation.

The idea is that if we have a lot of elements handled in a similar way, then instead of assigning a handler to each of them — we put a single handler on their common ancestor.

In the handler we get event.target to see where the event actually happened and handle it.

e.stopImmediatePropagation() is used for Stopping Event Bubbling with delegation.

11. What is Currying and give an example?

Ans: Currying is a transformation of a function which is used to call a function with a series of argument as function(a)(b)©

function addition(a) {
return function(b) {
return function(c) {
return a + b + c;
}
}
}let result = addition(1)(2)(3);
console.log(result); // -> 6

12. How many types of data type are there in JavaScript and what is the difference between null and undefined.

Ans: There are two type of Data types are in JavaScript they are primitive and non primitive.

Types of Primitive data types: pass by value or immutable.

i. number,

ii. string,

iii. boolean,

iv. null,

v. undefined,

vi. symbol

Type of Non Primitive data types: pass by reference or mutable

i. Object,

ii. Function

Difference between null and undefined:

null: The variable which is assigned to a value null, in JavaScript null is an object.

undefined: The variable which is declared and not assigned which returns a value undefined.

13. Is Object in JavaScript are call by value or call by reference?

Ans: In JavaScript, Objects are call by reference not by value.

let obj1 = {
name: "angular"
}let obj2 = {
name: "angular"
}let obj3 = obj1;console.log(obj1 === obj2); // -> false;
console.log(obj1 === obj3); // -> true; call by reference

14. What is the difference between Shallow copy and deep copy, and he gives an example and check your understanding?

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

let obj1 = {
name: "angular",
version: 8};let obj2 = {
name: "angular",
version: 9
};obj2.version = 10;
console.log(obj1.version); // Your output

15. What is the new feature of ES 6 and do you like function based programming or class based programming?

Ans: ES 6 provide many new feature are,

i. block level scope with let and const,

ii. class

iii. Arrow function

iv. spread and rest operator,

v. for/of loop

vi. template string

vii. promises,

viii.map, set, weak map, weak set

17. Write a Fibonacci Series program? Where he will check you coding strategy how you are writing the code.

function fibonacci(num)
{
var num1=0;
var num2=1;
var sum;
var i=0;
for (i = 0; i < num; i++)
{
sum=num1+num2;
num1=num2;
num2=sum;
}
return num2;
}

18. How do you implement interface in JavaScript?

First of all, there is not built in support for traditional abstraction in JavaScript. At least, there are not any types like interfaces and abstract classes. However, interface can be implemented using Object.create method and prototypes.

19. How do you select element in JavaScript and he will ask which one you are using most?

To select a <select> element, you use the DOM API like getElementById() or querySelector() .

20. What is design patterns and which one you are using in your project?

JavaScript modules are the most prevalently used design patterns for keeping particular pieces of code independent of other components. This provides loose coupling to support well-structured code.

For those that are familiar with object-oriented languages, modules are JavaScript “classes”. One of the many advantages of classes is encapsulation — protecting states and behaviors from being accessed from other classes. The module pattern allows for public and private (plus the lesser-know protected and privileged) access levels.

21. Difference between let, const and var and what is scoping in JavaScript?

var declarations are globally scoped or function scoped while let and const are block scoped. var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared. They are all hoisted to the top of their scope

22. How to create private and public method in JavaScript?

There are no private, public or protected keywords in current ECMAScript 6 specification.

So Traceur does not support private and public. 6to5 (currently it's called "Babel") realizes this proposal for experimental purpose (see also this discussion). But it's just proposal, after all.

So for now you can just simulate private properties through WeakMap (see here). Another alternative is Symbol - but it doesn't provide actual privacy as the property can be easily accessed through Object.getOwnPropertySymbols.

IMHO the best solution at this time — just use pseudo privacy. If you frequently use apply or call with your method, then this method is very object specific. So it's worth to declare it in your class just with underscore prefix:

class Animal {    _sayHi() {
// do stuff
}
}

23. Difference ways to create Object in JavaScript?

Creating object with a constructor

Using object literals

Creating object with Object.create() method

Using es6 classes

24. What is prototype chaining?

Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. … Nearly all objects in JavaScript are instances of Object which sits on the top of a prototype chain.

25. What is pure function?

A pure function is a function which: Given the same input, will always return the same output. Produces no side effects.

26. difference between freeze and seal in object?

seal() allows changes to the existing properties of an object whereas Object. freeze() does not allow so. Object. freeze() makes an object immune to everything even little changes cannot be made.

27.Difference between Object.create() and Object.assign()?

Create method is used to create object instance with an already declared object properties and it’s prototype and assign it to a newly created prototype object and return’s empty object. Assign method is used to assign object properties from source object to the target object and also return’s the new object.

28. What is a callback function?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

function greeting(name) {
alert('Hello ' + name);
}

function processUserInput(callback) {
var name = prompt('Please enter your name.');
callback(name);
}

processUserInput(greeting);

29. How do achieve asynchronous operations in JavaScript?

Asynchronous programming makes it possible to express waiting for long-running actions without freezing the program during these actions. JavaScript environments typically implement this style of programming using callbacks, functions that are called when the actions complete.

30. Difference between async/await and promise and which is best to use?

Promise creation starts the execution of asynchronous functionality. await only blocks the code execution within the async function. It only makes sure that the next line is executed when the promise resolves. So, if an asynchronous activity has already started, await will not have any effect on it.

31. What is the difference ways to create functions in JavaScript?

Ans: There are five ways to write a function in JavaScript,

i. function declaration,

ii. function expression,

iii. arrow function,

iv. Self invoking function (IIFE),

v. Anonymous Function

32. How do you increase JavaScript code performance step by step?

Cache in the browser

Define the execution context

Remove unused JavaScript

Avoid using too much memory

Defer the load of JavaScript that is not necessary

Avoid memory leaks

Use web workers when you need to execute code that needs a lot of execution time

33. How do you debug your JavaScript code and which one you prefer a lot?

Debugging is not easy. But fortunately, all modern browsers have a built-in JavaScript debugger.

Built-in debuggers can be turned on and off, forcing errors to be reported to the user.

With a debugger, you can also set breakpoints (places where code execution can be stopped), and examine variables while the code is executing.

Normally, otherwise follow the steps at the bottom of this page, you activate debugging in your browser with the F12 key, and select “Console” in the debugger menu.

35. What is NaN and how do you check if a value is a number type?

The isNaN() function determines whether a value is an illegal number (Not-a-Number). This function returns true if the value equates to NaN. Otherwise it returns false. This function is different from the Number specific Number

36. What is a Singleton class in JS and how do you create one?

The Singleton Pattern limits the number of instances of a particular object to just one. This single instance is called the singleton.

Singletons are useful in situations where system-wide actions need to be coordinated from a single central place. An example is a database connection pool. The pool manages the creation, destruction, and lifetime of all database connections for the entire application ensuring that no connections are ‘lost’.

Singletons reduce the need for global variables which is particularly important in JavaScript because it limits namespace pollution and associated risk of name collisions. The Module pattern (see our Dofactory JS product) is JavaScript’s manifestation of the Singleton pattern.

var Singleton = (function () {
var instance;

function createInstance() {
var object = new Object(“I am the instance”);
return object;
}

return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();

function run() {

var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();

37. Give me some example of different array methods in JavaScript and its uses?

The push() method adds a new element to an array (at the end)

pop() method removes the last element from an array

shift() method removes the first array element and "shifts" all other elements to a lower index

unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements

splice() method can be used to add new items to an array

concat() method creates a new array by merging (concatenating) existing arrays

slice() method slices out a piece of an array into a new array

38. What is Event Bubbling?

Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors of the target element in the same nesting hierarchy till it reaches the outermost DOM element or document object

39. What is Event Capturing?

Event capturing is the event starts from top element to the target element. It is the opposite of Event bubbling, which starts from target element to the top element

41. Difference between prototype and __proto__?

__proto__ is the actual object that is used in the lookup chain to resolve methods, etc. prototype is the object that is used to build __proto__ when you create an object with new:

( new Foo ).__proto__ === Foo.prototype;
( new Foo ).prototype === undefined;

42. What is the difference between setTimeout() and setInterval() and how to stop both?

The only difference is , setTimeout() triggers the expression only once while setInterval() keeps triggering expression regularly after the given interval of time. (unless you tell it to stop). To stop further calls, we should call clearInterval(timerId)

43. How to delete property of an Object?

The delete operator deletes a property from an object

44. How to get only keys from an Object?

Object.keys()

45. Difference between Synchronous and Asynchronous?

Synchronous and asynchronous transmissions are two different methods of transmission synchronization. Synchronous transmissions are synchronized by an external clock, while asynchronous transmissions are synchronized by special signals along the transmission medium

46. How to add property to an Object dynamically?

Yes it is possible. Assuming:

var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
var propertyName = "someProperty";
var propertyValue = "someValue";

Either:

data[propertyName] = propertyValue;

47. What does browser store in localStorage and sessionStorage?

window. localStoragestores data with no expiration date. window. sessionStoragestores data for one session (data is lost when the browser tab is closed)

48. What is the difference between localStorage and sessionStorage?

sessionStorage is similar to localStorage ; the difference is that while data in localStorage doesn’t expire, data in sessionStorage is cleared when the page session ends. A page session lasts as long as the browser is open, and survives over page reloads and restores.

49. Where do you store JWT token?

A JWT needs to be stored in a safe place inside the user’s browser. If you store it inside localStorage, it’s accessible by any script inside your page (which is as bad as it sounds, as an XSS attack can let an external attacker get access to the token). Don’t store it in local storage (or session storage)

50. What is spread and rest operator and its difference?

The spread operator allows us to spread the value of an array (or any iterable) across zero or more arguments in a function or elements in an array (or any iterable). The rest parameter allows us to pass an indefinite number of parameters to a function and access them in an array.

51. How to copy two array into new array?

  1. Using variable assignment. This method has side effects as changes to the element of an array reflects on both the places. …
  2. Create a new array of the same length and copy each element.
  3. Use the clone method of the array. Clone methods create a new array of the same size.
  4. Use System. arraycopy() method.

52. What is cookies and cache?

Cookies are files created by sites you visit. They make your online experience easier by saving browsing data. The cache remembers parts of pages, like images, to help them open faster during your next visit

54. Is callback function is a synchronous and asynchronous?

js all callbacks are synchronous unless you do something like setTimeOut or process. … js it’s more complicated: e.g. you can do file reading both synchronously and asynchronously. Then you just need to know that the callback is asynchronous by nature

55. Is JavaScript supports method over loading, if yes give me an example?

Ans: No, JavaScript doesn’t support method overloading, although we could write two methods with same name and different parameter. but Javascript call the last method which is defined.

function foo(a) {
console.log(a);
}function foo(a, b) {
console.log(a+b);
}console.log(foo(100)); //-> NaN

JavaScript calls the last function defined with name foo and where the second parameter was not passed and it returned NaN.

56. Difference between splice and slice method in an array?

The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object. 2. The splice() method changes the original array and slice() method doesn’t change the original array

58. How do you call method inside an IIFE function?

awesomeSauce.checkCode("Zorg!");

The IIFE returns an object with the checkCode property, that property is the (private) function.

The point of the IIFE is that this scopes the variables and functions within, so that they are not accessible from outside (e.g. privateCheckCode and secretCode exist only inside the IIFE).

Think of the returned object as an "export" of selected values or functionality.

59. Difference type of errors in JavaScript?

Syntax Errors

Runtime Errors

Logical Errors

The try…catch…finally Statement

The throw Statement

60. How to handle error in JavaScript?

using try, catch block.

61. Explain try, catch and finally block?

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. The finally statement lets you execute code, after try and catch, regardless of the result

62. How many ways you can make http request in JavaScript?

Ajax

jQuery methods

fetch

Axios

Angular HttpClient

62. Create a promise?

let promise = new Promise(function(resolve, reject) { // executor (the producing code, “singer”) });

63. What is the use of call, bind and apply method in JavaScript?

Ans: call, apply and bind is used to bind the scope of this from one object to a function. For Eg,

let Person = {
firstName: "angular",
lastName: "feed"
}function details(percentage) {
return `${this.firstName}${this.lastName} is ${percentage}% best site.`;
}

If we bind Person object in details function with call, then the first parameter should be the Person object and rest with comma separated value to details function.

details.call(Person, 100);

Note: call doesn’t return function, it calls as soon as we defined it and run.

apply: This work very similar to call but here we need to pass details function parameter as in array format.

details.apply(Person, [100]);

bind: bind will return a new function so, we can assign it to a variable and call it whenever required,

let getDetails = details.bind(Person, 100);
console.log(getDetails());

64. How do you get array index and value by using for/of loop?

Ans: Array index and value can be access by using de structuring and Array.entries() method in for/of loop,

let arr = ['10', '20', '30'];
for(let [index, value] of arr.entries()) {
console.log(`index: ${index} and value: ${value}`);
}

65. When did you use getter and setter in JavaScript, give an example?

class Account {
constructor(num, balance) {
this.num = num;
this.balance = balance;
}
}class Person extends Account {
constructor(perNum, perBal){
super(perNum, perBal);
} get accountNum() {
return this.num;
} set accBal(bal) {
this.balance = bal;
} set accNum(number) {
this.num = number;
} get accDetails() {
return `${this.num} + ${this.balance}`;
}
}let p = new Person('1234', 2000);
p.accBal = 4000;
p.accNum = 12345;
console.log(p.accDetails);

66. How to find Geo Location(longitude and latitude) of browser

The HTML Geolocation API is used to locate a user’s position

getCurrentPosition() method is used to return the user's position

The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location

70. What is the output of the following,

let i = 10;
console.log(typeof typeof i)

71. What is a higher order function?

A higher-order function is a function that can take another function as an argument, or that returns a function as a result

--

--

Pratibha

I am UI Architect and have experience in taking the interviews of 10 years. I have worked in All big Firms like Goldman, Morgan Stanley.