Javascript Interview Questions ( Topics )

pman47

Manish Prajapati

Posted on December 9, 2022

Javascript Interview Questions ( Topics )
  • What is Events?

    • JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page.
    • When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.
    • Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable.
    • Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code.

    JavaScript - Events


  • What are closures

    • A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

    Closures - JavaScript | MDN


  • Event bindings

    • When ever we want to bind any event with the HTML element then we are using addEventListner() or onclick attribute of HTML element, It is called Event Binding.
    document.getElementById(button).addEventListner(click,(){
        console.log("clicked");
    });
    
    document.getElementById(button).onClick = ()=>{
        console.log("clicked");
    }
    


  • Currying in js and it’s practical scenarios

    • It is a technique in functional programming, transformation of the function of multiple arguments into several functions of a single argument in sequence.
    // From This
    function calculate(a,b,c){
        return a+b+c;
    }
    calculate(1,2,3); // 6
    
    // To this
    const calculate = (a) => {
        return (b) => {
            return (c) => {
                return a+b+c;
            }
        }
    }
    
    calculate(1)(2)(3) // 6
    


  • Lexical scope in Js

    • A lexical scope in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration. But the opposite is not true; the variables defined inside a function will not be accessible outside that function.
    • In simple language, lexical scope is a variable defined outside your scope or upper scope is automatically available inside your scope which means you don't need to pass it there.
    var x = 2;
    var add = function() {
        var y = 1;
        return x + y;
    };
    

  • let const and var real uses

Five things to know about var, let, and const in JavaScript


  • Why arrow functions can not be hoisted

Can we use Hoisting with Arrow function ? - GeeksforGeeks


  • Event Bubbling and capturing

Event Bubbling and capturing

  • Event Bubbling

    • The bubbling principle is simple.
    • When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.
    • Let’s say we have 3 nested elements FORM > DIV > P with a handler on each of them:
    <form onclick="alert('form')">FORM
      <div onclick="alert('div')">DIV
        <p onclick="alert('p')">P</p>
      </div>
    </form>
    
    • When clicking on

      it will show alert() for p, then it will fire event of its parent that is

      ans so on.
    • To stop if event.stopPropagation() is used.
    <body onclick="alert(`the bubbling doesn't reach here`)">
      <button onclick="event.stopPropagation()">Click me</button>
    </body>
    
  • Event Capturing

    • Reverse of bubbling.
    • Parent to Child fire events.
    • document.getElementById(”click”,()⇒{},true);

    • Event Propagation
      • Event Propagation determines in which order the elements receive the event. There are two ways to handle this event propagation order of HTML DOM is Event Bubbling and Event Capturing.
      • For example, suppose there are three components namely component1component2component3. Inside these components, we attached the onClickEventListener event handlers. Now when we click on component3 the event handler for all the three components will be executed. Now here the question is in which order the event will execute. Now at this point event bubbling and capturing comes into the picture.

    • Event Delegation

      • Event Delegation is basically a pattern to handle events efficiently. Instead of adding an event listener to each and every similar element, we can add an event listener to a parent element and call an event on a particular target using the .target property of the event object.

      Event Delegation in JavaScript - GeeksforGeeks


    • use strict

      • Strict mode makes it easier to write "secure" JavaScript.
      • Strict mode changes previously accepted "bad syntax" into real errors.
      • As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
      • In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.
      • In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.

      JavaScript "use strict"


    • Call, Apply and Bind

      • Bind

        • The bind() method creates a new function that, when called, has its this keyword set to the provided value.
        var pokemon = {
            firstname: 'Pika',
            lastname: 'Chu ',
            getPokeName: function() {
                var fullname = this.firstname + ' ' + this.lastname;
                return fullname;
            }
        };
        
        var pokemonName = function() {
            console.log(this.getPokeName() + 'I choose you!');
        };
        
        var logPokemon = pokemonName.bind(pokemon); // creates new object and binds pokemon. 'this' of pokemon === pokemon now
        
        logPokemon(); // 'Pika Chu I choose you!'
        
        • Let’s break it down. When we use the bind() method:
          1. the JS engine is creating a new pokemonName instance and binding pokemon as its this variable. It is important to understand that it copies the pokemonName function.
          2. After creating a copy of the pokemonName function it is able to call logPokemon(), although it wasn’t on the pokemon object initially. It will now recognizes its properties (Pika and Chu) and its methods.
        • And the cool thing is, after we bind() a value we can use the function just like it was any other normal function
      • Call & Apply

        • The call() method calls a function with a given this value and arguments provided individually.
        • What that means, is that we can call any function, and explicitly specify what this should reference within the calling function. Really similar to the bind() method! This can definitely save us from writing hacky code (even though we are all still hackerzzz).
        • The main differences between bind() and call() is that the call() method:
          1. Accepts additional parameters as well
          2. Executes the function it was called upon right away.
          3. The call() method does not make a copy of the function it is being called on.
        • call() and apply() serve the exact same purpose. The only difference between how they work is that call() expects all parameters to be passed in individually, whereas apply() expects an array of all of our parameters.
        var pokemon = {
            firstname: 'Pika',
            lastname: 'Chu ',
            getPokeName: function() {
                var fullname = this.firstname + ' ' + this.lastname;
                return fullname;
            }
        };
        
        var pokemonName = function(snack, hobby) {
            console.log(this.getPokeName() + ' loves ' + snack + ' and ' + hobby);
        };
        
        pokemonName.call(pokemon,'sushi', 'algorithms'); // Pika Chu  loves sushi and algorithms
        pokemonName.apply(pokemon,['sushi', 'algorithms']); // Pika Chu  loves sushi and algorithmsShallow
        

        Javascript: call(), apply() and bind()


    • Shallow Copy & Deep Copy

      • Shallow Copy

        • The shallow copy of an object will refer to same memory of original array.
        let a = [1,2,3,4] // Memory Address : 10225
        let b = a;        // Memory Address : 10225 (same)
        b.push(5)         // Changes in b
        console.log(a)    // [1,2,3,4,5]
        
      • Deep Copy

        • The memory reference will not be same while copying using deep copy method.
        • Using Spread Operator Or map.
        let a = [1,2,3,4]
        let b = a.map((e)=>e);
        b.push(5)
        console.log(a) //[1,2,3,4]
        -------- OR --------
        let b = [...a];
        

    • Event Loop

      • Call Stack - (First global execution context will passed)
      • Callback Queue - (Task Queue)
      • Microtask Queue - (Higher Priority Then Callback queue)
      • Event Loop

      JS Visualizer 9000


    • Debouncing and Throttling
      • The major difference between debouncing and throttling is that debounce calls a function when a user hasn’t carried out an event in a specific amount of time, while throttle calls a function at intervals of a specified amount of time while the user is carrying out event.
      • For example, if we debounce a scroll function with a timer of 250ms (milliseconds), the function is only called if the user hasn’t scrolled in 250ms. If we throttle a scroll function with a timer of 250ms, the function is called every 250ms while the user is scrolling.
      • Debouncing
        • Debouncing.png
      • Throttling
        • throttling.png


💖 💪 🙅 🚩
pman47
Manish Prajapati

Posted on December 9, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Javascript Interview Questions ( Topics )
javascript Javascript Interview Questions ( Topics )

December 9, 2022

133. Clone Graph
javascript 133. Clone Graph

June 8, 2022