Header Ads Widget

Advance JavaScript interview Questions for professionals.

Javascript is a simple yet very complex and weird language. You may hate it sometimes because of its buggy nature. But if you understand the core concepts, you will love this language. Each front-end developer goes through the journey of hate and love for this language. The more you understand the language the more you fall in love with it.
For an experienced or professional developer, it is very important to understand the core concepts deeply. Below is the list of Javascript interview questions that an experienced front-end dev must know. You can checkout beginner/Internediate level quesitions too, because they are also very very important for the interview.

advance javascript interview question

Advance JavaScript interview questions list

  1. How to handle exceptions in JavaScript?
  2. What id Temporal Dead Zone in JavaScript?
  3. How can we make an Object ReadOnly, so that it can't be editable?
  4. What is prototype?
  5. How does Prototypal innheritance work?
  6. What is prototype chain?
  7. What is scope chain and lexical scope?
  8. What is polyfill in JavaScript? Write an example.
  9. What is difference between call(), bind() and apply()?
  10. What is execution context?
  11. How can we change the execution context of a functions?
  12. What is Memory leaking? Give an example of memory leak?
  13. How garbage collector works in JavaScript?
  14. What is event loop?
  15. What is event delegation? What is difference between event bubbling and capturing?
  16. What is debouncing and Throttling? Give a real time example for both.
  17. What is Design patterns? Give some example which you have used or know in javascript?
  18. What is service worker?
  19. How can you implement data streaming?
  20. What is PWA?
  21. How can you achieve static typing in JavaScript?
  22. What is anti-pattern in JavaScript?

1. How to handle exceptions in JavaScript?

Javascript provides try/catch to handle the exceptions. It works pretty much the same as other programming languages. The try block- where we write our block of code, the catch block- where we handle errors and the finally block where we write a block of code which is executed regardless of try/catch.

try {
  Block of code to try
}
catch(err) {
  Block of code to handle errors
}
finally {
  Block of code to be executed regardless of the try / catch result
}

2. What id Temporal Dead Zone in JavaScript?

let and const are also hoisted like var and function, but they are not assigned with undefined in the creation phase. They exist but without any value and we can’t access them until they are assigned a value. This period between the hoisted declaration and value assignment is called temporal dead zone (TDZ). let and const declarations do hoist, but they throw errors when accessed before being initialized.

function test() {
    // start TDZ for x
    console.log(a); //Reference error
    let a = 'local value'; // declaration ends TDZ for x
};

3. How can we make an Object ReadOnly, so that it can't be editable?

We can use Object.freeze() to make ann object ReadOnly. It does not allow editing/deleting or changing the value. We can alternnatively use Object.defineProperties() to achieve this.

var obj = {id: 1};
Object.freeze(obj);
var obj = {id: 1};
obj.id = 5; 
//it do not affect the original value, it ramains 1

Object.defineProperties(obj, {
  id: {
    writable: false
  }
});
obj.id = 5; 
//it do not affect the original value, it ramains 1

3.1 What is difference between Object.freeze() and Object.seal()?

Object.freeze() and Object.seal() both are used to create non extensible objects (means- we can not add/delete properties of object). But Object.seal() allow editing the existing value which we can't do with Object.freeze().

var obj = {id: 1};
Object.freeze(obj);
var obj = {id: 1};
obj.id = 5; 
//it do not affect the original value, it ramains 1

var obj = {id: 1};
Object.freeze(obj);
var obj = {id: 1};
obj.id = 5; 
console.log(obj); //output- {id: 5}

4. What is prototype?

Prototype is an object that is associated with every function and object in JavaScript. Prototypes allow us to attach methods or properties to it which can be later accessed by all the instances of that object. Methods and properties attached to the prototype are stored at one place in the memory and every instance of the object has access to it, hence it helps in performance enhancement.

  function Student(name){
    this.name = name;
  }
  Student.prototype.commonInfo = {
      schoolName: "ABC school",
      board: "CBSE",
  }

  var st1 = new Student("Neil");
  var st2 = new Student("Joe");

  console.log(st1); //OUTPUT: {name: "Neil"}
  console.log(st2); //OUTPUT: {name: "Joe"}
  console.log(st1 === st2); //OUTPUT: false
  console.log(st1.board === st2.board); //OUTPUT: true
   

As you can see in the above example, commonInfo is a property which holds some common Information for all the students. When we crerate a new Student object, commonInfo becomes part of the __proto__ object. This __proto__ object is nothing but the prototype object which hold all the prototype information. One thing to note here commonInfo is stored in a sinle place in the memory and referennced by all the student objects. Thats why when we compare st1.board === st2.board it returns true.

5. How does Prototypal innheritance work?

In the above Student constructor example, you have seen how the commonInfo is inherited to all the student object. It is one of the examples of prototypal inheritance.

Prototypal innheritance

In the above example, car and bike both inherit from the vehicle.

In the above Student constructor example, you have seen how the commonInfo is inherited to all the student object. It is one of the examples of prototypal inheritance. Javascript has this special prototype object which is associated with each object. You can access this object using __propt__ key. __propt__ is the object which holds all the values from the parent object. When we try to access any property of an object, javascript engine looks for that property within that object. If not found, it looks within __propt__ object. There can be a chain of a prototype. Javascript engine keeps looking for the property until it reaches the root of the chain that is Object. That's how we can implement prototype inheritance. For example:- Object.toStrint() is inherited to all the object from Object.

6. What is prototype chain?

     var vehicle = {
      runs: true,
      info: function(){ 
         console.log('Vehicle- ', this.name, '
         , engine- ', this.engine);  
      }  
    };
    var car = {
      wheels: 4
    };
    var bike = {
      wheels: 2
    };

    car.__proto__ = vehicle;
    bike.__proto__ = vehicle;

    var honda = {
        name: "Honda",
        engine: "250CC"
    }
    var mercedes = {
        name: "Mercedes",
        engine: "2000CC"
    }
    honda.__proto__ = bike; 
    mercedes.__proto__ = car;

    honda.info();//Output: Vehicle-  Honda , engine-  250CC
    mercedes.info();//Output: Vehicle-  Mercedes , engine-  2000CC
     

In the above example, info is a method definend in vehicle, but honda and mercedes objects are able to access them info. It is able to access the name and engine through prototype chain.

From above we have understood how prototype inheritance works. When we try to access any property of an object, javascript engine looks for that property within that object. If not found, it looks within __propt__ object. Javascript engine keeps looking for the property until it reaches the root of the chain that is Object. This is what the prototype chain is.

Prototype act as a link between two objects. A series of objects linked together via prototypes is called the prototype chain."

7. What is scope chain and lexical scope?

Remember closure concept- A inner function has access to its outer environment members. Scope chain works on this principle only. If a function does not find the property within, it tries to find it within the parent scope and continue until it reaches the global scope. This is called scope chain.
Lexical scope- Javascript engine determines the scope at compile time rather than runtime. The JavaScript engine uses the lexical environment to store the variables during the program execution. By seeing the source code we can tell the value of a variable. This is called lexical scope.

8. What is polyfill in JavaScript? Write an example?

A polyfill is a piece of code that provides missing functionality on older browsers that do not natively support it. For example - Array.prototype.includes() is ECMAScript6. Older browsers will fail to execute this method. To provide this feature we can write a polyfill which will solve the problem.

      Array.prototype.map = function(fn) {
         var rv = [];	 
         for(var i=0, l=this.length; i<l; i++)
           rv.push(fn(this[i]));
        return rv;
      };
	

9. What is difference between call(), bind() and apply()?

call(), bind() and apply() is used to change the execution context of a function. Execution context is the this keyword. call(), apply()- both are same except the way they are used. call requires the arguments to be passed in one-by-one, and apply takes the arguments as an array. call and apply both execute the function immediately. There is a third method bind which does the same thing but it does not execute the function immediately, instead, it returns a reference which can be invoked later.

10. What is execution context?

When a function is defined, it is attached to its enclosing scope via closure. All the private members are statically bound, which means it can not be changed at runtime. However, a function has another characteristic known as the execution context, also known as this keyword. In a simple word, scope is static but the execution context is dynamic. execution context is entirely dependent on how it is called. Using call(), bind() and apply() we can dynamically change the execution context.

11. How can we change the execution context of a functions?

Execution context is dynamic and it is entirely dependent on how it is called. Either we can execute the function within another execution conntext or we can use call(), bind() and apply() to chage the execution context.

    function hostel(student) {
        return function study() {
            console.log(
                `${ student } wants to eat ${ this.food }`
            );
        };
    }
    var childFn = hostel("Kyle");
    var kyle = {
        food: 'Pizza',
        student: childFn //childFn is within kyle object execution context
    };
    kyle.student(); //Output: Kyle wants to eat Pizza
    childFn.call(kyle); //Output: Kyle wants to eat Pizza
    

12. What is Memory leaking? Give an example of memory leak?

A block of memory on the heap that is no longer used by the application and hasn’t been returned to the OS by the garbage collector. Accumulation of such blocks over the time could lead to the slowdown or crashing of the application or even the OS. You might have seen your screen froze sometime because your OS does not have enough memory. To avoid this we should make sure that we have not left any timers, unused global variables and members of a closure which is not in use.

13. How garbage collector works in JavaScript?

When we run a piece of code, all the variables within the scope of the code will be initialized in the memory. Once the execution is over and they are not being referenced from any other place then Garbage collector mark all of them and clean them from the memory. Javascript uses mark and sweep algorithm to do the garbage collection. Remember closure concept- A inner function holds the reference to its outer environment members. In this case, even though parent function execution is over, it does not garbage collect parent members because child function forms a closure.

14. What is event loop?

15. What is event delegation? What is difference between event bubbling and capturing?

Javascript is evet based language. When we click or press a key or scroll or move the mouse an event is generated. In javascript events are generally bubbled up or goes downwards from the top. It means, events start from target element and move to the upward direction to its parent, then the grandparent and so on until reaches the root of the HTML element. Similarly, events can move in the opposite direction - from root till target element, we need to set a flag for this. Event moving from top to bottom is called event capturing. Be it event bubbling or evet capturing, when we catch an event at some other element than the target element and do some activity then it is called event delegation. A simple example would be - attach an event at ul element than handling it at li elements.

16. What is debouncing and Throttling? Give a real time example for both.

17. What is Design patterns? Give some example which you have used or know in javascript?

Patterns are proven solutions and they provide solid approaches to solve issues in software development using proven. Patterns can be easily reused for similar kind of problems.
Reusing pattern can minimise the known problems - When we face a similar kind of problem we try to find a proven solution so that we do not have to reinvent the wheel. This will result in minimise the development time and we can focus on overall quality of product.

Design patterns in Javascript
  1. constructor pattern
  2. Module pattern
  3. Singleton pattern
  4. Prototype pattern
  5. Factory pattern

18. What is service worker?

Sservice worker is new feature in javascript. We can run a background thread apart from main thread. Thats means we ca serve request apart frorm main thread. It helps in implementing caching or retrieving resources from the cache, and delivering push messages. However, this background thread can not directly manipulate DOM elements. All the apis of servie worker are asynchronous in nature.

19. How can you implement data streaming?

19. What is PWA?

PWA stands for Progrerssive Web App. Web applications can be installed(add to homescreen) in mobile phones, they can receive notifications, they can have background jobs apart from the main thread. It can use deveice memory and implement offline capability. All these things are possible becasue of PWA.

20. How can you achieve static typing in JavaScript?

Yes, By using typescript we can achieve it.

21. What is anti-pattern in JavaScript?

A bad solution to a particular problem which resulted in a bad quality is called anti-pattern. A simple example would be - attaching similar event to thousands of list elemets instead delegating them to parent.

  • Polluting the global namespace by defining a large number of variables in the global context
  • Passing strings rather than functions to either setTimeout or setInterval as this triggers the use of eval() internally.
  • Modifying the Object class prototype (this is a particularly bad anti-pattern)
  • Using JavaScript in an inline form as this is inflexible
  • The use of document.write where native DOM alternatives such as document.createElement are more appropriate. document.write has been grossly misused over the years and has quite a few disadvantages including that if it's executed after the page has been loaded it can actually overwrite the page we're on, whilst document.createElement does not. We can see here for a live example of this in action. It also doesn't work with XHTML which is another reason opting for more DOM-friendly methods such as document.createElement is favorable.
  • Attaching same event listener (which does similar work) to all list items instead delegating it to parent.

Post a Comment

0 Comments