Join Regular Classroom : Visit ClassroomTech

JavaScript Interview Questions – Advanced Level | Codewindow.in

1. 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 (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element.

Example: If you click on EM, the handler on DIV runs.

<div onclick="alert('The handler!')">
  <em>If you click on <code>EM</code>, the handler on <code>DIV</code> runs.</em>
</div>
Stopping bubbling
<body onclick="alert(`the bubbling doesn\'t reach here`)">
  <button onclick="event.stopPropagation()">Click me</button>
</body>

2. What is event capturing?

Event capturing is a type of event propagation where the event is first captured by the outermost element and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the inner DOM element.

function Welcome(name) {
  var greetingInfo = function(message) {
    console.log(message+' '+name);
  }
  return greetingInfo;
}
var myFunction = Welcome('John');
myFunction('Welcome '); // Output: Welcome John
myFunction('Hello Mr.'); // output: Hello Mr.John

/* As per the above code, the inner function greetingInfo() has 
access to the variables in the outer function Welcome() even 
after outer function has returned. */

3. What is prototype chain?

Nearly all objects in JavaScript are instances of Object. That means all the objects in JavaScript inherit the properties and methods from Object.prototype. This is called Prototype chaining.

Prototype chaining is used to build new types of objects based on existing ones. It is similar to inheritance in a class based language. The prototype on object instance is available through Object.getPrototypeOf(object) or __proto__ property whereas prototype on constructors function is available through Object.prototype.

function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
}
//Person class created
Person.prototype.getFullName = function() {
  return this.firstName + " " + this.lastName;
}
// we have added getFullName method in Person’s prototype.
var person = new Person("John", "K", 25);
// It will create an instance of the Person class
> person.hasOwnProperty("firstName");  // true
> person.hasOwnProperty("getFullName");  // false
> person.getFullName(); // John K

4. What is a decorator?

A decorator is an expression that evaluates to a function and that takes the target, name, and decorator descriptor as arguments. Also, it optionally returns a decorator descriptor to install on the target object. Let us define admin decorator for user class at design time:

function admin(isAdmin) {
  return function(target) {
      target.isAdmin = isAdmin;
  }
}
@admin(true)
class User() {
}
console.log(User.isAdmin); //true
@admin(false)
class User() {
}
console.log(User.isAdmin); //false

5. What is a comma operator?

The comma operator is used to evaluate each of its operands from left to right and returns the value of the last operand. This is totally different from comma usage within arrays, objects, and function arguments and parameters. For example, the usage for numeric expressions would be as below,

var x = 1;
x = (x++, x);
console.log(x); // 2

C QA

Mostly Asked

DS QA

Mostly Asked

DBMS QA

Mostly Asked

ML QA

Mostly Asked

6. Example of Prototypal Inheritance?

We already have a build-in Object.create, but if you were to provide a polyfill for it, that might look like:

if (typeof Object.create !== 'function') {
  Object.create = function (parent) {
    function Tmp() {}
    Tmp.prototype = parent;
    return new Tmp();
  };
}
const Parent = function() {
  this.name = "Parent";
}
Parent.prototype.greet = function() { console.log("hello from Parent"); }
const child = Object.create(Parent.prototype);
child.cry = function() {
  console.log("waaaaaahhhh!");
}
child.cry();
// Outputs: waaaaaahhhh!
child.greet();
// Outputs: hello from Parent

/*
Things to note are:
.greet is not defined on the child, so the engine goes up the prototype chain and finds .greet off the inherited from Parent.
We need to call Object.create in one of following ways for the prototype methods to be inherited:
*/

Object.create(Parent.prototype);
Object.create(new Parent(null));
Object.create(objLiteral);
// Currently, child.constructor is pointing to the Parent:
child.constructor
ƒ () {
  this.name = "Parent";
}
/*
child.constructor.name
"Parent"
If we'd like to correct this, one option would be to do:
*/
function Child() {
  Parent.call(this);
  this.name = 'child';
}
Child.prototype = Parent.prototype;
Child.prototype.constructor = Child;
const c = new Child();
c.cry();
// Outputs: waaaaaahhhh!
c.greet();
// Outputs: hello from Parent
c.constructor.name;
// Outputs: "Child"

7. What do you think of AMD vs CommonJS?

Both are ways to implement a module system, which was not natively present in JavaScript until ES2015 came along. CommonJS is synchronous while AMD (Asynchronous Module Definition) is obviously asynchronous. CommonJS is designed with server-side development in mind while AMD, with its support for asynchronous loading of modules, is more intended for browsers.
I find AMD syntax to be quite verbose and CommonJS is closer to the style you would write import statements in other languages. Most of the time, I find AMD unnecessary, because if you served all your JavaScript into one concatenated bundle file, you wouldn’t benefit from the async loading properties. Also, CommonJS syntax is closer to Node style of writing modules and there is less context-switching overhead when switching between client side and server side JavaScript development.
I’m glad that with ES2015 modules, that has support for both synchronous and asynchronous loading, we can finally just stick to one approach. Although it hasn’t been fully rolled out in browsers and in Node, we can always use transpilers to convert our code.

8. What are the pros and cons of using Promises instead of callbacks?

Pros
Avoid callback hell which can be unreadable.
Makes it easy to write sequential asynchronous code that is readable with .then().
Makes it easy to write parallel asynchronous code with Promise.all().
With promises, these scenarios which are present in callbacks-only coding, will not happen:
Call the callback too early
Call the callback too late (or never)
Call the callback too few or too many times
Fail to pass along any necessary environment/parameters
Swallow any errors/exceptions that may happen
Cons
Slightly more complex code (debatable).
In older browsers where ES2015 is not supported, you need to load a polyfill in order to use it.

9. What is the definition of a higher-order function?

A higher-order function is any function that takes one or more functions as arguments, which it uses to operate on some data, and/or returns a function as a result. Higher-order functions are meant to abstract some operation that is performed repeatedly. The classic example of this is map, which takes an array and a function as arguments. map then uses this function to transform each item in the array, returning a new array with the transformed data. Other popular examples in JavaScript are forEach, filter, and reduce. A higher-order function doesn’t just need to be manipulating arrays as there are many use cases for returning a function from another function. Function.prototype.bind is one such example in JavaScript.
Map

// Let say we have an array of names which we need to transform each string to uppercase.
const names = ['irish', 'daisy', 'anna'];
The imperative way will be as such:
const transformNamesToUppercase = function(names) {
  const results = [];
  for (let i = 0; i < names.length; i++) {
    results.push(names[i].toUpperCase());
  }
  return results;
};
transformNamesToUppercase(names); // ['IRISH', 'DAISY', 'ANNA']
// Use .map(transformerFn) makes the code shorter and more declarative.
const transformNamesToUppercase = function(names) {
  return names.map(name => name.toUpperCase());
};
transformNamesToUppercase(names); // ['IRISH', 'DAISY', 'ANNA']

10. Can you give an example of a curry function and why this syntax offers an advantage?

Currying is a pattern where a function with more than one parameter is broken into multiple functions that, when called in series, will accumulate all of the required parameters one at a time. This technique can be useful for making code written in a functional style easier to read and compose. It is important to note that for a function to be curried, it needs to start out as one function, then broken out into a sequence of functions that each accepts one parameter.

function curry(fn) {
  if (fn.length === 0) {
    return fn;
  }
  function _curried(depth, args) {
    return function(newArgument) {
      if (depth - 1 === 0) {
        return fn(...args, newArgument);
      }
      return _curried(depth - 1, [...args, newArgument]);
    };
  }
  return _curried(fn.length, []);
}
function add(a, b) {
  return a + b;
}
var curriedAdd = curry(add);
var addFive = curriedAdd(5);
var result = [0, 1, 2, 3, 4, 5].map(addFive); // [5, 6, 7, 8, 9, 10]

11. What is the difference between undefined and not defined in JavaScript?

In JavaScript if you try to use a variable that doesn’t exist and has not been declared, then JavaScript will throw an error var name is not defined and the script will stop executing thereafter. But If you use typeof undeclared_variable then it will return undefined.

/* 
Before starting further discussion Let us understand the difference between declaration and definition.
*/
var x is a declaration because you are not defining what value it holds yet, but you are declaring its existence and the need for memory allocation.
var x; // declaring x
console.log(x); // output: undefined
/* 
var x = 1 is both declaration and definition (also we can say we are doing initialisation), 
Here declaration and assignment of value happen inline for variable x, In JavaScript every variable declaration and function declaration 
brings to the top of its current scope in which It is declared then assignment happen in order this term is called hoisting.

A variable can be declared but not defined. When we try to access it, It will result undefined.
*/

var x; // Declaration
typeof x === 'undefined'; // Will return true
// A variable can be neither declared nor defined. When we try to reference such variable then the result will be not defined.
console.log(y);  // Output: ReferenceError: y is not defined

12. How to empty an array in JavaScript?

For instance:
var arrayList = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’];
How can we empty the array above?
There are a couple of ways by which we can empty an array, So Let us discuss all the possible way by which we can empty an array.

Method 1

arrayList = [];

The code above 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 code above will clear the existing array by setting its length to 0. This way of emptying an array will also update all the reference variables that point to the original array.

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.

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

The Array.isArray() method determines whether an object is an array. This function returns true if the object is an array, and false if not.

 // Creating some variables
  var v1 = {name: "John", age: 22};   
  var v2 = ["red", "green", "blue", "yellow"];
  var v3 = [10, 20, 30, 40, 50];
  var v4 = null;
  // Testing the variables data type
  typeof(v1); // Returns: "object"
  typeof(v2); // Returns: "object"
  typeof(v3); // Returns: "object"
  typeof(v3); // Returns: "object"
  // Testing if the variable is an array
  Array.isArray(v1);  // Returns: false
  Array.isArray(v2);  // Returns: true
  Array.isArray(v3);  // Returns: true
  Array.isArray(v4);  // Returns: false
/*
Note: The Array.isArray() method is supported in all major browsers, such as Chrome, Firefox, IE (9 and above)
*/

14. What is undefined x 1 in JavaScript?

var trees = [“redwood”, “bay”, “cedar”, “oak”, “maple”];
delete trees[3];

When you run the code above and do console.log(trees); in chrome developer console then you will get [“redwood”, “bay”, “cedar”, undefined × 1, “maple”].
In the recent versions of Chrome you will see the word empty of undefined x 1.
When you run the same code in Firefox browser console then you will get [“redwood”, “bay”, “cedar”, undefined, “maple”]

Clearly we can see that Chrome has its own way of displaying uninitialized index in arrays. However when you check trees[3] === undefined in any browser you will get similar output as true.

Note: Please remember that you need not check for the uninitialized index of the array in trees[3] === ‘undefined × 1’ it will give an error because ‘undefined × 1’ this is just way of displaying an uninitialized index of an array in chrome.

15. Calculate the length of the associative array?

var counterArray = {
A : 3,
B : 4
};
counterArray[“C”] = 1;
First of all, in case of JavaScript an associative array is the same as an object. Secondly, even though is no built-in function or property available to calculate the length/size an object, we can write such function ourselves.

Method 1
Object has keys method which can we used to calculate the length of object.
Object.keys(counterArray).length; // Output 3


Method 2
We can also calculate the length of object by iterating through the object and by doing a count of own property of object. This way we will ignoge the properties that came from the object’s prototype chain:
function getLength(object) {
var count = 0;
for(key in object) {
// hasOwnProperty method check own property of object
if(object.hasOwnProperty(key)) count++;
}
return count;
}

Method 3
All modern browsers (including IE9+) support the getOwnPropertyNames method, so we can calculate the length using the following code:
Object.getOwnPropertyNames(counterArray).length; // Output 3

Method 4
Underscore and lodash libraries have the method size dedicated to calculate the object length. We don’t recommend to include one of these libraries just to use the size method, but if It is already used in your project – why not?
_.size({one: 1, two: 2, three: 3});
=> 3

16. What are Service Workers and when can you use them?

It is a technology that allows your web application to use cached resources first, and provide default experience offline, before getting more data from the network later. This principle is commonly known as Offline First.
Service Workers actively use promises. A Service Worker has to be installed,activated and then it can react on fetch, push and sync events.
As of 2017, Service Workers are not supported in IE and Safari.

Categories
Pages
Recent Posts