Javascript Interview Questions ( Topics )
Tags: javascript, programming, tutorial, career
Published: 2022-12-09 14:56:02

- **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](https://www.tutorialspoint.com/javascript/javascript_events.htm)
    
---
- **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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)
    
---
- **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.
    
    ```jsx
    document.getElementById(’button’).addEventListner(”click”,()⇒{
    	console.log("clicked");
    });
    
    document.getElementById(’button’).onClick = ()=>{
    	console.log("clicked");
    }
    ```
---
- **Arrow Function**
    - Introduced in ES6
    - Arrow functions allow us to write shorter function syntax :
    
    ```jsx
    let myFunction = (a, b) => a * b;
    ```
    
    [Arrow function expressions - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)

---
- **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.
    
    ```jsx
    // 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
    ```
    
---
- **Memoization in Js**
    - Memoization ****is an optimization technique used primarily to speed up computer programs by **storing the results of expensive function calls** and returning the cached result when the same inputs occur again
    
    [How to use Memoize to cache JavaScript function results and speed up your code](https://www.freecodecamp.org/news/understanding-memoize-in-javascript-51d07d19430e/)

---
- **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.
    
    ```jsx
    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](https://www.educative.io/answers/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](https://www.geeksforgeeks.org/can-we-use-hoisting-with-arrow-function/)

---
- **Event Bubbling and capturing**


![Event Bubbling and capturing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rrgpqxrj1zlvyf1j36p6.png)

- **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:
    
    ```jsx
    <form onclick="alert('form')">FORM
      <div onclick="alert('div')">DIV
        <p onclick="alert('p')">P</p>
      </div>
    </form>
    ```
    
    - When clicking on <p> it will show alert() for p, then it will fire event of its parent that is <div> ans so on.
    - To stop if **event.stopPropagation()** is used.
    
    ```jsx
    <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 *component1*, *component2*, *component3.* 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](https://www.geeksforgeeks.org/event-delegation-in-javascript/)

---
- **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"](https://www.w3schools.com/js/js_strict.asp)

---
- **Call, Apply and Bind**
    - **Bind**
        - The **`bind()`** method creates a new function that, when called, has its `this` keyword set to the provided value.
        
        ```jsx
        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.
        
        ```jsx
        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()](https://medium.com/@omergoldberg/javascript-call-apply-and-bind-e5c27301f7bb)
        
---
- **Shallow Copy & Deep Copy**
    - Shallow Copy
        - The shallow copy of an object will refer to same memory of original array.
        
        ```jsx
        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.
        
        ```jsx
        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](https://www.jsv9000.app/)
    
---
- **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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xma8oc0iefua2au49zmp.png)
    - **Throttling**  
        - ![throttling.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ebmf5oinv86pvfmo00pv.png)