{"id":21231558,"url":"https://github.com/piyalidas10/javascript-interview-questions-mylists","last_synced_at":"2025-07-03T02:34:54.890Z","repository":{"id":120845924,"uuid":"589433206","full_name":"piyalidas10/Javascript-Interview-Questions-Mylists","owner":"piyalidas10","description":"Javascript Interview Questions","archived":false,"fork":false,"pushed_at":"2024-11-17T15:27:18.000Z","size":8048,"stargazers_count":5,"open_issues_count":1,"forks_count":2,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-11-17T16:34:16.820Z","etag":null,"topics":["interview","interview-questions","javascript"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/piyalidas10.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-01-16T05:07:55.000Z","updated_at":"2024-11-17T15:27:22.000Z","dependencies_parsed_at":"2024-10-25T06:41:38.137Z","dependency_job_id":"552c1cb5-8c10-48d2-ae40-cf25c8e2a3b7","html_url":"https://github.com/piyalidas10/Javascript-Interview-Questions-Mylists","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/piyalidas10%2FJavascript-Interview-Questions-Mylists","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/piyalidas10%2FJavascript-Interview-Questions-Mylists/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/piyalidas10%2FJavascript-Interview-Questions-Mylists/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/piyalidas10%2FJavascript-Interview-Questions-Mylists/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/piyalidas10","download_url":"https://codeload.github.com/piyalidas10/Javascript-Interview-Questions-Mylists/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225648976,"owners_count":17502183,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["interview","interview-questions","javascript"],"created_at":"2024-11-20T23:47:17.976Z","updated_at":"2025-07-03T02:34:54.872Z","avatar_url":"https://github.com/piyalidas10.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Javascript-Interview-Questions\nJavascript Interview Questions\n\n### 1. Pure function vs Impure functions\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n\n- Pure functions do not have side effects. Impure functions can cause side effects.\n- Pure functions return the same output if we use the same input parameters. However, impure functions give different outcomes when we pass the same arguments multiple times.\n- Pure functions always return some results. Impure functions can execute without producing anything.\n- Debugging pure functions is relatively easier than debugging impure functions.\n- Pure functions cannot execute AJAX calls or standard DOM manipulation.\n- Impure functions aren’t inherently wrong. They merely can cause some confusion in more extensive systems in the form of spaghetti code.\n\n`Pure Functions`\nTo get a better understanding, let’s consider the following example.\n```\nfunction add(a,b) { \n  return a + b\n}\nconsole.log(add(4,5))\n```\nThis example contains a simple add() function, which gives 9 as the output. It is a very predictable output, and it does not depend on any external code. This makes the add() function a pure function.\n\n`Impure Functions`\nFor example, consider the following code snippet:\n```\nvar addNew = 0;\nfunction add(a,b){ \n  addNew =1; \n  return a + b + addNew\n}\nconsole.log(add(4,5))\n```\nIn the above example, there is a variable named addNew, and it is declared outside of the add() function. But the state of that variable is changed inside the add() function. So, the add() function has a side effect on a variable outside of its scope and is therefore considered an impure function.\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 2. What is Javascript closure ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n  #### \n  https://medium.com/@piyalidas.it/closure-in-javascript-2496fdedeb7d\n  https://dev.to/imranabdulmalik/mastering-closures-in-javascript-a-comprehensive-guide-4ja8#:~:text=The%20Factory%20Function%20Pattern%20uses,without%20explicitly%20class%2Dbased%20syntax.\n  \n  Closure provides access to the outer scope of a function from inside the inner function, even after the outer function has closed. The main advantage of javascript closure is Data Privacy.\n\n  ```\n  const countFunc = function counter() {\n     let c = 0;\n     c = c+1;\n    return c;\n  }();\n```\n  If you run countFunc, eveytime it will print \"1\". This you can resolve by closure.\n  \n  Solution using normal function\n  ------------------------------------------\n  const countFunc = function counter() {\n     let c = 0;\n     return function() {\n         c = c+1;\n         return c;\n     }\n  }();\n  run countFunc()\n  \n  Solution using arrow function\n  ------------------------------------------\n  ```\n  const countFunc = function counter() {\n     let c = 0;\n     return ()=\u003e {\n         c = c+1;\n         return c;\n     }\n  }();\n  run countFunc()\n  ```\n\n  The variable countFunc is assigned to the return value of a self-invoking function.\n  \nWhen to Use Closure in JavaScript (Practical use)?\n  Suppose, you want to count the number of times user clicked a button on a webpage. For this, you are triggering a function on onclick event of button to update the count of the variable\n ```\n\u003cbutton onclick=\"updateClickCount()\"\u003eclick me\u003c/button\u003e\n ```\nNow there could be normal approaches like:\n  You could use a global variable, and a function to increase the counter:\n   ```\n   var counter = 0;\n   function updateClickCount() {\n       ++counter;\n       // Do something with counter\n   }\n   ```\n  But, the pitfall is that any script on the page can change the counter, without calling updateClickCount().\n  ou might be thinking of declaring the variable inside the function:\n  ```\n   function updateClickCount() {\n       var counter = 0;\n       ++counter;\n       // Do something with counter\n   }\n  ```\n  But, hey! Every time updateClickCount() function is called, the counter is set to 1 again.\n  you need to find a way to execute counter = 0 only once not everytime. SO have to use closure.\n  ```\n  \u003cscript\u003e\n  var updateClickCount = (function(){\n      var counter = 0;\n  \n      return function(){\n          ++counter;\n          document.getElementById(\"spnCount\").innerHTML = counter;\n      }\n  })();\n  \u003c/script\u003e\n  \n  \u003chtml\u003e\n  \u003cbutton onclick=\"updateClickCount()\"\u003eclick me\u003c/button\u003e\n  \u003cdiv\u003e you've clicked\n      \u003cspan id=\"spnCount\"\u003e 0 \u003c/span\u003e times!\n  \u003c/div\u003e\n  \u003c/html\u003e\n  ```\n \n \u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 3. Javascript Event Loop\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n  https://www.jsv9000.app/\n  \n  ![JavaScript Visualizer 9000](https://github.com/piyalidas10/Javascript-Interview-Questions-Mylists/blob/main/images/jsv9000.gif)\n  \n  ```\n  function three() {\n  console.log(\"three\");\n\n  setTimeout(function () {\n    console.log(\"last\");\n  }, 1000);\n}\n\nfunction two() {\n  console.log(\"two\");\n  three();\n}\n\nfunction one() {\n  console.log(\"one\");\n  two();\n}\n\none();\n```\n  ![JavaScript Visualizer 9000](https://github.com/piyalidas10/Javascript-Interview-Questions-Mylists/blob/main/images/event_loop_1.gif)\n  \n  JavaScript is single-threaded: only one task can run at a time. Usually that’s no big deal, but now imagine you’re running a task which takes 30 seconds.. Ya.. During that task we’re waiting for 30 seconds before anything else can happen (JavaScript runs on the browser’s main thread by default, so the entire UI is stuck) 😬 It’s 2019, no one wants a slow, unresponsive website.\n\nLuckily, the browser gives us some features that the JavaScript engine itself doesn’t provide: a Web API. This includes the DOM API, setTimeout, HTTP requests, and so on. This can help us create some async, non-blocking behavior.\n\n\nWhen we invoke a function, it gets added to something called the call stack. The call stack is part of the JS engine, this isn’t browser specific. It’s a stack, meaning that it’s first in, last out (think of a pile of pancakes). When a function returns a value, it gets popped off the stack.\n  \n![popped off the stack](https://github.com/piyalidas10/Javascript-Interview-Questions-Mylists/blob/main/images/call_stack.gif)\n\n\nThe respond function returns a setTimeout function. The setTimeout is provided to us by the Web API: it lets us delay tasks without blocking the main thread. The callback function that we passed to the setTimeout function, the arrow function () =\u003e { return 'Hey' } gets added to the Web API. In the meantime, the setTimeout function and the respond function get popped off the stack, they both returned their values!\n\n![setTimeout](https://github.com/piyalidas10/Javascript-Interview-Questions-Mylists/blob/main/images/setTimeout.gif)\n\n\nIn the Web API, a timer runs for as long as the second argument we passed to it, 1000ms. The callback doesn’t immediately get added to the call stack, instead it’s passed to something called the queue.\n\n![callback_queue](https://github.com/piyalidas10/Javascript-Interview-Questions-Mylists/blob/main/images/callback_queue.gif)\n\n\nThis can be a confusing part: it doesn't mean that the callback function gets added to the callstack(thus returns a value) after 1000ms! It simply gets added to the queue after 1000ms. But it’s a queue, the function has got to wait for its turn!\n\nNow this is the part we’ve all been waiting for… Time for the event loop to do its only task: connecting the queue with the call stack! If the call stack is empty, so if all previously invoked functions have returned their values and have been popped off the stack, the first item in the queue gets added to the call stack. In this case, no other functions were invoked, meaning that the call stack was empty by the time the callback function was the first item in the queue\n\n![event_loop](https://github.com/piyalidas10/Javascript-Interview-Questions-Mylists/blob/main/images/event_loop.gif)\n\n\nThe callback is added to the call stack, gets invoked, and returns a value, and gets popped off the stack.\n\n![callstack_executed](https://github.com/piyalidas10/Javascript-Interview-Questions-Mylists/blob/main/images/callstack_executed.gif)\n\n\nReading an article is fun, but you'll only get entirely comfortable with this by actually working with it over and over. Try to figure out what gets logged to the console if we run the following:\n\n```\nconst foo = () =\u003e console.log(\"First\");\nconst bar = () =\u003e setTimeout(() =\u003e console.log(\"Second\"), 500);\nconst baz = () =\u003e console.log(\"Third\");\n\nbar();\nfoo();\nbaz();\n```\n\nGot it? Let's quickly take a look at what's happening when we're running this code in a browser:\n\n![output](https://github.com/Javascript-Interview-Questions-Mylists/blob/main/images/output.gif)\n\n- 1. We invoke bar. bar returns a setTimeout function.\n- 2. The callback we passed to setTimeout gets added to the Web API, the setTimeout function and bar get popped off the callstack.\n- 3. The timer runs, in the meantime foo gets invoked and logs First. foo returns (undefined),baz gets invoked, and the callback gets added to the queue.\n- 4. baz logs Third. The event loop sees the callstack is empty after baz returned, after which the callback gets added to the call stack.\n- 5. The callback logs Second.\n  \n  \n \u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 4. Slice vs Splice\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n\n- 1. Slice is used to get a new array from the original array whereas the splice is used to add/remove items in the original array. The changes are not reflected in the original array in the case of slice and in the splice, the changes are reflected in the original array.\n```\n--------- Slice-----------\nlet arr = [4, 3, 5, 9];\nlet res = arr.slice(0, 2);\nconsole.log(res); --------- (2) [4, 3]\n\n-----------Splice----------\nlet arr = [4, 3, 5, 9];\narr.splice(0, 2);\nconsole.log(arr); --------- (2) [5, 9]\n```\n- 2. The splice() method is used to add or remove elements of an existing array \n```\n--------- Add element-----------\nlet arr = [4, 3, 5, 9];\narr.splice(2, 0, 10);\nconsole.log(arr); ---------- (5) [4, 3, 10, 5, 9]\n\n--------- Remove element-----------\nlet arr = [4, 3, 5, 9];\narr.splice(2, 1);\nconsole.log(arr); ---------- (3) [4, 3, 9]\n```\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 5. Spread vs Rest\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n\nThe spread operator helps us expand an iterable such as an array where multiple arguments are needed, it also helps to expand the object expressions.\n    var array1 = [10, 20, 30, 40, 50];\n    var array2 = [60, 70, 80, 90, 100];\n    var array3 = [...array1, ...array2];\n    console.log(array3);       [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\n  \n    const obj = {\n        firstname: \"Divit\",\n        lastname: \"Patidar\",\n    };\n    const obj2 = { ...obj };\n    console.log(obj2);\n    {\n        firstname: \"Divit\",\n        lastname: \"Patidar\"\n    }\n  \nThe rest parameter syntax allows a function to accept an indefinite number of arguments as an array.\n  \n  ```\n  function myBio(firstName, lastName, ...otherInfo) {\n    return otherInfo;\n  }\n\n  console.log(\n    myBio('Oluwatobi', 'Sofela', 'CodeSweetly', 'Web Developer', 'Male')\n  );\n  [\"CodeSweetly\", \"Web Developer\", \"Male\"]\n  ```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 5. Event Propagation ( Event Bubbling and capturing )\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n  \n#### \n  ![bubbling-and-capturing](https://javascript.info/article/bubbling-and-capturing/eventflow.svg)\n  \u003cbr\u003e\n- 1. Capturing phase – the event goes down to the element.\n- 2. Target phase – the event reached the target element.\n- 3. Bubbling phase – the event bubbles up from the element.\n  \nEvent capturing means propagation of event is done from ancestor elements to child element in the DOM while event bubbling means propagation is done from child element to ancestor elements in the DOM. \u003cbr\u003e\n  \n  ![bubbling-and-capturing](https://github.com/piyalidas10/Javascript-Interview-Questions-Mylists/blob/main/images/LsIr2.png)\n  \u003cbr\u003e\nDOM Events describes 3 phases of event propagation: Capturing phase – the event goes down to the element. Target phase – the event reached the target element. Bubbling phase – the event bubbles up from the element.\n  \nBoth can be prevented by using the stopPropagation() method.\n\n```\n\u003cform onclick=\"alert('form')\"\u003eFORM\n  \u003cdiv onclick=\"alert('div')\"\u003eDIV\n    \u003cp onclick=\"alert('p')\"\u003eP\u003c/p\u003e\n  \u003c/div\u003e\n\u003c/form\u003e\n```\nSo if we click on \u003cp\u003e, then we’ll see 3 alerts: p → div → form.\nThe process is called “bubbling”, because events “bubble” from the inner element up through parents like a bubble in the water.\n\nevent.stopPropagation() stops the move upwards\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n\n### 6. Top 10 Features of ES6 \n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n\nhttps://www.boardinfinity.com/blog/top-10-features-of-es6/\n\u003cbr\u003e\n\n- 1. let and const Keywords\n- 2. Arrow Functions\n- 3. Multi-line Strings\n- 4. Default Parameters\n- 5. Template Literals\n- 6. Destructuring Assignment\n- 7. Enhanced Object Literals\n- 8. Promises\n- 9. Classes\n- 10. Modules\n\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 7. What is Recursion?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nRecursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a result.\n```\nfunction factorial(num) { \n   if(num \u003c= 0) { \n      return 1; \n   } else { \n      return (num * factorial(num-1)  ) \n   } \n} \nconsole.log(factorial(6)) \n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 8. What is Temporal Dead Zone?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nTemporal Dead Zone is the period of time during which the let and const declarations cannot be accessed.\nTemporal Dead Zone starts when the code execution enters the block which contains the let or const declaration and continues until the declaration has executed.\nVariables declared using let and the constants declared using const are hoisted but are in a TDZ. \n\n```\nconsole.log(a);\nvar a = 10;\nIt will print ----------- undefined\n\nconsole.log(a);\nlet a = 10;\nIt will print ----------- VM228:1 Uncaught ReferenceError: a is not defined\n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 9. map() vs forEach()\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nThe map() method is used to transform the elements of an array, whereas the forEach() method is used to loop through the elements of an array. The map() method can be used with other array methods, such as the filter() method, whereas the forEach() method cannot be used with other array methods.\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 10. What is prototype in javascript\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nPrototypes are the mechanism by which JavaScript objects inherit features from one another. The prototype is an object that is associated with every functions and objects by default in JavaScript. \nWhen a programmer needs to add new properties like variables and methods at a later point of time, and these properties need sharing across all the instances, then the prototype will be very handy.\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 11. When to use Prototype in JavaScript?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nAs we all know, Javascript is a dynamic language where we can add new variables and methods to the object at any point in time, as shown below.\n```\nfunction Employee() {\n    this.name = 'Arun';\n    this.role = 'QA';\n}\n\nvar empObj1 = new Employee();\nempObj1.salary = 30000;\nconsole.log(empObj1.salary); // 15\n\nvar empObj2 = new Employee();\nconsole.log(empObj2.salary); // undefined\n```\nAs we see in the above example, the salary variable adds to the empObj1. But when we try to access the salary variable using the empObj2 object, it doesn't have the salary variable because the salary variable is defined only in the empObj1 object.\n\nNow comes the question, Can there be a way that the new variable can be added to the function itself so as it is accessible to all the objects created using the function?\n\nThe answer to this question is the use of a prototype. A prototype is an invisible inbuilt object which exists with all the functions by default. The variables and methods available in the prototype object can be accessible, modifiable, and even can create new variables and functions.\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 12. prototype inheritance in javascript\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nPrototype inheritance in javascript is the linking of prototypes of a parent object to a child object to share and utilize the properties of a parent class using a child class.\nThe syntax used for prototype inheritance has the __proto__ property which is used to access the prototype of the child. The syntax to perform a prototype inheritance is as follows :\n\nchild.__proto__ = parent;\n\n```\nlet animal = {\n    animalEats: true,\n};\n\nlet rabbit = {\n    rabbitJumps: true,\n};\n\n// Sets rabbit.[[Prototype]] = animal\nrabbit.__proto__ = animal;\nconsole.log(rabbit.animalEats); // true\nconsole.log(rabbit.rabbitJumps); // true\n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 13. Remove duplicate values from Array\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\narr = [1, 2,3,4,5,6,2,3,4];\nfinalArr = [...new Set(arr)];  ///////  [1, 2, 3, 4, 5, 6]\n\narr = [1, 2, 3, 3, 4, 5, 6];\nconst finalArr1 = arr.reduce((acc, curElm) =\u003e {\n    return acc.includes(curElm)? acc : [...acc, curElm]\n},[]);\nconsole.log(finalArr1); // [1, 2, 3, 4, 5, 6]\nconst finalArr2 = arr.reduce((acc, curElm) =\u003e {\n    return acc.includes(curElm)? acc : acc.concat(curElm)\n},[]);\nconsole.log(finalArr2); // [1, 2, 3, 4, 5, 6]\n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 14. Removing duplicate objects (based on multiple keys) from array\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\nconst listOfTags = [\n    {id: 1, label: \"Hello\", color: \"red\", sorting: 0},\n    {id: 2, label: \"World\", color: \"green\", sorting: 1},\n    {id: 3, label: \"Hello\", color: \"blue\", sorting: 4},\n    {id: 4, label: \"Sunshine\", color: \"yellow\", sorting: 5},\n    {id: 5, label: \"Hello\", color: \"red\", sorting: 6},\n]\n\nconst unique = [];\n\nlistOfTags.map(x =\u003e unique.filter(a =\u003e a.label == x.label \u0026\u0026 a.color == x.color).length \u003e 0 ? null : unique.push(x));\n\nconsole.log(unique);\n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 15. Why JavaScript is a single-thread language ? \n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nThe JavaScript within a chrome browser is implemented by a V8 engine.\n\nMemory Heap\nCall Stack\nMemory Heap: It is used to allocate the memory used by your JavaScript program. Remember memory heap is not the same as the heap data structures, they are totally different. It is the free space inside your OS.\n\nCall Stack: Within the call stack, your JS code is read and gets executed line by line.\n\nNow, JavaScript is a single-threaded language, which means it has only one call stack that is used to execute the program. The call stack is the same as the stack data structure that you might read in Data structures. As we know stacks are FILO that is First In Last Out. Similarly, within the call stack, whenever a line of code gets inside the call stack it gets executed and moves out of the stack. In this way, JavaScript is a single-thread language because of only one call stack.\n\nJavaScript is a single-threaded language because while running code on a single thread, it can be really easy to implement as we don’t have to deal with the complicated scenarios that arise in the multi-threaded environment like a deadlock.\n\nSince JavaScript is a single-threaded language, it is synchronous in nature. Now, you will wonder if you have used async calls in JavaScript so is it possible then?\n\nSo, let me explain to you the concept of async calls within JavaScript and how it is possible with single-threaded language. Before explaining it let’s discuss briefly why we require the async call or asynchronous calls. As we know within the synchronous calls, all the work is done line by line i.e. the first task is executed then the second task is executed, no matter how much time one task will take. This arises the problem of time wastage as well as resource wastage. These two problems are overcome by asynchronous calls, where one doesn’t wait for one call to complete instead it runs another task simultaneously. So, when we have to do things like image processing or making requests over the network like API calls, we use async calls.\n\nNow, coming back to the previous question of how to use async calls within JS. Within JS we have a lexical environment, syntax parser, and an execution context (memory heap and call stack) that is used to execute the JS code. But these browsers also have Event Loops, Callback queue, and WebAPIs that are also used to run the JS code. Although these are not part of JS it also helps to execute the JS properly as we sometimes used the browser functions within the JS.e);\n\n  ![JavaScript Runtime Environment](https://github.com/piyalidas10/Javascript-Interview-Questions-Mylists/blob/main/images/single-threaded.jpg)\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 16. How can i make array immutable in javascript\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nIn JavaScript, things that are immutable don’t change in value when you use them, and things that are mutable do.\nObject. freeze() to arrays to make them immutable. \n\n```\nFor example, lets create a variable, age1, and assign its value to another variable, age2. If we update age2, the original variable, age1, is unaffected.\n// Create a variable\nlet age1 = 42;\n// Assign it to a new variable\nlet age2 = age1;\n// Update the new variable\nage2 = 84;\n// logs 42\nconsole.log(age1);\n```\n\nYou can create an immutable copy of an array using Array.slice() with no arguments, or with the Array.from() method. It’s considered a best practice to do so before manipulating an array.\n```\n// Create an immutable copy\nlet evenMoreSandwiches = Array.from(sandwiches);\n// Add a few sandwiches\nsandwiches.push('italian', 'blt');\n// logs [\"turkey\", \"ham\", \"pb\u0026j\", \"italian\", \"blt\"]\nconsole.log(sandwiches);\n// logs [\"turkey\", \"ham\", \"pb\u0026j\"]\nconsole.log(evenMoreSandwiches);\n```\nYou can use the spread operator to create immutable copies of arrays and objects instead of use Array.from().\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 17. How can i make object immutable in javascript\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nYou can create an immutable copy of an object using Object.assign(). Pass in an empty object ({}) as the first argument and the object you want to copy as the second.\n\nIt’s considered a best practice to do so before manipulating an object.\n```\n// Create an immutable copy\nlet evenMoreLunch = Object.assign({}, lunch);\n// Add a snack\nlunch.snack = 'cookies';\n// Logs {sandwich: 'turkey', drink: soda, snack: 'cookies'}\nconsole.log(lunch);\n// Logs {sandwich: 'turkey', drink: soda}\nconsole.log(evenMoreLunch);\n```\nYou can use the spread operator to create immutable copies of arrays and objects instead of use Object.assign().\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 18. How can reduce Memory Leaks in Javascript ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nmost of the memory leaks can be traced back to not removing all references to objects that you don't need anymore. This can happen when you forget to remove intervals or timers, or you make excessive use of global variables.\nStoring data in global variables is probably the most common type of memory leak. In the browser, for instance, if you use var instead of const or let—or leave out the keyword altogether—the engine will attach the variable to the window object.\nThe same will happen to functions that are defined with the function keyword.\n```\nuser = getUser();\nvar secondUser = getUser();\nfunction getUser() {\n  return 'user';\n}\n```\nAll three variables, user, secondUser, and getUser, will be attached to the window object.\nThis only applies to variables and functions that are defined in the global scope. If you want to learn more about this, check out this article explaining the JavaScript scope.\nAvoid this by running your code in strict mode.\nApart from adding variables accidentally to the root, there are many cases in which you might do this on purpose.\nYou can certainly make use of global variables, but make sure you free space up once you don't need the data anymore.\nTo release memory, assign the global variable to null.\n```\nwindow.users = null;\n```\nSo something to keep in mind is that memory is limited. When it comes to a call stack and memory Heap, those are two places is where javascript runs and stores memory. So we have to be careful not to have memory leaks or stack overflow if we are to have efficient code.\n\nOn the frontend, you can profile the memory usage in the Chrome DevTools under the Memory tab.\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n### 19. Why JavaScript is single threaded?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n\n![CallStack](https://github.com/piyalidas10/Javascript-Interview-Questions-Mylists/blob/main/images/javascript_call_stack.gif)\n\nJavaScript can do one single thing at a time because it has only one call stack.\nThe call stack is a mechanism that helps the JavaScript interpreter to keep track of the functions that a script calls.\nEvery time a script or function calls a function, it's added to the top of the call stack. Every time the function exits, the interpreter removes it from the call stack.\nA function either exits through a return statement or by reaching the end of the scope.\n\nEvery time a function calls another function, it's added to the top of the stack, on top of the calling function.\nThe order in which the stack processes each function call follows the LIFO principle (Last In, First Out).\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 20. Primitive vs Non-Primitive\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nPrimitive data types\n----------------------------------------------------------------------\nExamples of Primitive data types are Boolean, char, byte, int, short, long, float, and double.\n\nbasic data types for whom memory is allocated in stack.\nA stack is a data structure that JavaScript uses to store static data. Static data is data where the engine knows the size at compile time. In JavaScript, this includes primitive values (strings, numbers, booleans, undefined, and null) and references, which point to objects and functions.\nSince the engine knows that the size won't change, it will allocate a fixed amount of memory for each value.\nThe process of allocating memory right before execution is known as static memory allocation.\nBecause the engine allocates a fixed amount of memory for these values, there is a limit to how large primitive values can be.\nThe limits of these values and the entire stack vary depending on the browser.\n\nReference (non primitive) data types\n----------------------------------------------------------------------\n1.\tFunction – typeof function is function\n2.\tArray – typeof array is object\n3.\tObject – typeof object is object\n4.\tDate – typeof date is object\n\nMemory allocated for reference data types is in heap ( dynamic memory allocation).\nThe heap is a different space for storing data where JavaScript stores objects and functions.\nUnlike the stack, the engine doesn't allocate a fixed amount of memory for these objects. Instead, more space will be allocated as needed.\nAllocating memory this way is also called dynamic memory allocation.\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 21. What is garbage collector ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n\nIn javascript, memory should be cleared up automatically using a thing called Garbage collector. Javascript is a language who ha garbage collector meaning you don't have to manage your memory manually. It gets cleared automatically \u0026 assigned automatically.\n\nGarbage collector consists of three steps : 1. Find the root node in your code and recursively go through every child. The root node of browser code is Window object. In Nodejs , window object is global variable. 2. Mark every child including the root as active or inactive. Active means this part of code is referenced in the memory. Inactive mens it's not referenced from anywhere. 3. Delete all these inactive ones which mean if the variable i not needed anymore in the memory simple delete it. \n\nwindow.x = 10   it's a global variable. you probably heard many times is a realy bad practive to have global variables. \nwindow.calc  = function() =\u003e {}  calc is a fuction and imagine it does something heavy inside. That's obviously gonna stay on the root becuase root is accessing it and garbage collectors think that is always active becuase it sits on the root. \nFirst thing you can do use strict to prevent you from these memory leaks becuae it i going to throw errors as soon as you have global variables. Or simple not use any global variables. \n\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 22. Difference Between Null \u0026 Undefined ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n\nUndefined means the variable has been declared, but its value has not been assigned. Null means an empty value or a blank value.\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 23. What will be the output of undefined==null \u0026 undefined===null ? Why ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n\nundefined==null will be true because both undefined and null represent nothingness.\nundefined===null will be false because they contain different data type because undefined and null are different in terms of data type.\n\n typeof(undefined) // 'undefined' \u003cbr/\u003e\n typeof(null) // 'object'\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 24. What is Hosting ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nIn JavaScript, hoisting refers to the built-in behavior of the language through which declarations of functions, variables, and classes are moved to the top of their scope – all before code execution. Hoisting only happen with var and function keywords. \n\n  console.log(x);\n  var x = 9;\n  it will print undefined becuase at runtime it will be executed like the following way =:\u003e\n  var x;\n  console.log(x);\n  x = 9;\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 25. var vs let ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n![var_let](https://github.com/piyalidas10/Javascript-Interview-Questions-Mylists/blob/main/images/var_let.png)\nvar is function scoped and let is block scoped. Variables declared by let are only available inside the block where they’re defined. Variables declared by var are available throughout the function in which they’re declared.\n\n    console.log(x);\n    var x=5;\n    Output will be undefined\n    \n    console.log(x);\n    let x=5;\n    Output will be ReferenceError: Cannot access 'x' before initialization\n    \n    let variables are not initialized until their definition is evaluated. Accessing them before the initialization results in a ReferenceError. The variable is said to be in \"temporal dead zone\" from the start of the block until the initialization is processed.\n![var_let](https://github.com/piyalidas10/Javascript-Interview-Questions-Mylists/blob/main/images/temporal_dead_zone.png)\n    \nWhen working outside of function bodies, at a global level, let does not create a property on the global object, whereas var does. Therefore:\n    // Global variables\n    var x = 1;\n    let y = 2;\n    console.log(this.x); // will print 1\n    console.log(this.y); // will print undefined\n    \n    {\n      let name1 = \"Aryan\" // name1 in block scope\n      console.log(name1) // Aryan\n    }\n\n    {\n      var newName = \"Kaush\" // newName not in block scope as var is used\n      console.log(newName) // Kaush\n    }\n\n    console.log(name1) // ReferenceError\n    console.log(newName) // Kaush    \n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 26. What is Arrow function ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n  Arrow functions do not have their own arguments and it uses the arguments from the outer function.\n  \n  - This object does not work with arrow function.\n  - arguments object does not work with arrow function.\n  - you cannot use new to call arrow function.\n \n ```\n  const obj = {\n    test() {\n        console.log(this);\n    }\n  };\n  obj.test() ==== {test: ƒ}\n\n  const obj = {\n      test:()=\u003e{\n          console.log(this);\n      }\n  };\n  obj.test() ======== Window{0: Window, window: Window, self: Window, document: document, name: '', location: Location,…}\n\n  function show() {\n      console.log(arguments);\n  }\n  show(1,2,3); ======== Arguments(3)[1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]\n\n  const show = ()=\u003e {\n      console.log(arguments);\n  }\n  show(1,2,3); ======== Uncaught ReferenceError: arguments is not defined\n  \n  solution for that --------\n  const show = (...arg)=\u003e {\n      console.log(arg);\n  }\n  show(1,2,3); ========(3)[1, 2, 3]\n  ```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 27. What is IIFE(Immediately Invoked Function Expression) ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \na JavaScript function which calls itself, runs as soon as it is defined. This pattern encapsulates code within its own scope, preventing variable pollution in the global scope and enabling more controlled and modular code organization. \n```\n    (function(){\n      console.log(\"IIFE\");\n    })();\n```\n\n\u003cstrong\u003eUse Cases\u003c/strong\u003e\u003cbr/\u003e\n\u003cstrong\u003eEncapsulation:\u003c/strong\u003e IIFEs are commonly used to encapsulate variables and functions, preventing them from polluting the global scope. This is particularly useful in large applications or when integrating third-party scripts.\u003cbr/\u003e\n\u003cstrong\u003eAvoiding Variable Collision:\u003c/strong\u003e By creating a separate scope, IIFEs help prevent variable names from conflicting with those in other scripts or libraries, thus improving code robustness.\u003cbr/\u003e\n\u003cstrong\u003eModule Pattern:\u003c/strong\u003e Before ES6 introduced modules, IIFEs were often used to create modules with private and public methods, providing a way to structure code and manage dependencies effectively.\u003cbr/\u003e\n\n\u003cstrong\u003eModule Pattern Before ES6\u003c/strong\u003e\n```\nvar module = (function() {\n    var privateVariable = 'I am private';\n\n    function privateFunction() {\n        return 'Private function';\n    }\n\n    return {\n        publicVariable: 'I am public',\n        publicFunction: function() {\n            return 'Public function calls ' + privateFunction();\n        }\n    };\n})();\n\nconsole.log(module.publicVariable); // Outputs: I am public\nconsole.log(module.publicFunction()); // Outputs: Public function calls Private function\n```\nHere, privateVariable and privateFunction() are encapsulated within the IIFE’s scope, while publicVariable and publicFunction() are exposed and accessible outside.\n\n\u003cstrong\u003eFor Loop with var Before ES6\u003c/strong\u003e\nAnother common use case of IIFEs was to handle for loops with var, preventing unintended closures:\n```\nfor (var i = 0; i \u003c 5; i++) {\n    (function(index) {\n        setTimeout(function() {\n            console.log(index);\n        }, 1000);\n    })(i);\n}\n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 28. What is Call, Bind, Apply ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nbind() - creates a new function with predefined this value and returns it.\ncall() and apply() execute functions immediately with the specified this value. , but call() accepts arguments individually while apply() accepts an array of arguments.\n\n\u003cb\u003ePractical Scenario ::=\u003c/b\u003e\n```\n  function show(obj) {\n      console.log(this);\n  }\n  let obj = {\n    a: 5\n  }\n```\n  show(obj) will print Window {0: Window, window: Window, self: Window, document: document, name: '', location: Location, …}\n  \n  Now I want that show function should bind to this object and not the window object, which is the global object. So purpose of this function is at the moment I want to assign the object reference tool that this object. Now call is handy for this scenario.\n  The call method takes first argument as the object to be passed to this. Then whatever parameters you want to pass, it's absolutely fine.\n  \n  show.call(obj) will print {a: 5}\n  So in short call is used to change the reference or context are in charge value of this object.\n\n```\n  const person = {\n    firstName: 'John',\n    lastName: 'Doe',\n    getFullName: function() {\n      return `${this.firstName} ${this.lastName}`;\n    }\n  };\n\n  const logName = function() {\n    console.log(`Logged name: ${this.getFullName()}`);\n  }\n  \n  // bind logName to person object\n  const logPersonName = logName.bind(person); \n  \n  logPersonName(); // will output \"Logged name: John Doe\"\n```\n  Now call is handy for this scenario. When we want to bind the object but will call later.\n  \n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 29. What are the use of Map \u0026 Set ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n    let product = new Map();\n    product.set('pCode', '001');\n    =====\u003e Map(1) {'pCode' =\u003e '001'}\n    product.set(1, '002');\n    =====\u003e Map(2) {'pCode' =\u003e '001', 1 =\u003e '002'}\n    product.set(true, '003');\n    =====\u003e Map(3) {'pCode' =\u003e '001', 1 =\u003e '002', true =\u003e '003'}\n    product.size  =====\u003e 3\n    product.get(1) =====\u003e '002'\n  \n    let product = new Set(['one', 'two', 'three', 'two']);\n    product =====\u003e Set(3) {'one', 'two', 'three'}\n    let arr = [1, 2, 3, 4, 2, 5];\n    arr = [...new Set(arr)];  =====\u003e (5) [1, 2, 3, 4, 5]\n  \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 30. Delete/Remove a property from an Object ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nUsing delete operator\n    let emp = {\n    name: \"Kareem\",\n    age: 26,\n        designation: \"Software Engineer\",\n    }\n    delete emp.age\n    console.log(emp)  =====\u003e  {name: 'Kareem', designation: 'Software Engineer'}\n\nUsing rest operator\n    let emp = {\n        name: \"Kareem\",\n        age: 26,\n        designation: \"Software Engineer\",\n    }\n    const {age, ...newEmp} = emp;\n    console.log(newEmp);  =====\u003e  {name: 'Kareem', designation: 'Software Engineer'}\n  \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 31. Difference Between == (loose equality) and === (strict equality operator) in Javascript ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nThe == operator checks if two values are equal.\n\n    let a = '10', b = 10;    \n    a == b          =====\u003e      true\n    a === b         =====\u003e      false\n  \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 32. Anonymous Functions in JavaScript ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nAnonymous functions in JavaScript, are the functions that do not have any name or identity.\n    let variableName = function () {\n        //your code here\n    }\n    variableName();     //Can call the anonymous function through this\n\nUse of Anonymous functions : \n    button.addEventListener('click', \n        function(event) {\n        alert('Button is clicked!')\n    });\n    \n    setTimeout(function () {\n        console.log('I will run after 5 seconds!')\n    }, 5000);\n    \n    Using Anonymous Functions as Arguments of Other Functions\n    function greet(wish){\n      console.log(wish() ,\"everyone!\");\n    }\n    greet(function(){\n      return \"Good Morning\";\n    })\n    \n    Immediately Invoked Function Execution\n    (function(text) {\n      alert(text);\n    })('Hi all! Welcome to our page.');\n    \n    for (var i = 1; i \u003c= 5; i++) {\n        (function (count) {\n            setTimeout(function() {\n                console.log(`Counted till ${count} after ${count} seconds`);\n            }, 1000 * i);\n        })(i);\n    }\n    Output:\n    \"Counted till 1 after 1 second\"\n    \"Counted till 2 after 2 seconds\"\n    \"Counted till 3 after 3 seconds\"\n    \"Counted till 4 after 4 seconds\"\n    \"Counted till 5 after 5 seconds\"\n  \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 33. Difference between Document Object \u0026 Window Object ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nthe entire browser window is actually window object and the inner part where the content is displayed, all the content can be accessed using the document object. This also means that window is the main container or patterned or global object and document is child of window object operations related to entire browser.\n![window](https://github.com/piyalidas10/Javascript-Interview-Questions-Mylists/blob/main/images/window.png)\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 34. Rest Operator: Delete property from an Object using Rest operator ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n      let user = {\n          name: 'Calvin',\n          age: 200,\n          country: 'Spain',\n          food: 'Pizza'\n      }\n      const {age, ...restOfUser} = user;\n      console.log(restOfUser)  // { name: 'Calvin', country: 'Spain', food: 'Pizza' }\n      console.log(age)       // 200\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 35. What is Object destructuring?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nObject destructuring allows us to create variables from object property names, and the variable will contain the value of the property name - for example:\n\n    const data = { a: 1, b: 2, c: 3 };\n    const { a, b, c } = data;\n    console.log(a, b, c); // 1, 2, 3\n    By using const { a, b, c } = data we are declaring 3 new variables (a, b and c).\n    If a, b and c exist as property names on data, then variables will be created containing the values of the object properties. If the property names do not exist, you’ll get undefined.\n    \n    Let’s take our earlier example and use the ...rest syntax to see what happens:\n    const data = { a: 1, b: 2, c: 3 };\n    const { a, ...rest } = data;\n    console.log(a); // 1\n    console.log(rest); // { b: 2, c: 3 }\n\n    let arr = [1, 2, 3, 4];\n    let [a,,c,d] = arr;\n    console.log(a,c,d); // 1 3 4\n\n    let a = 4;\n    let b = 9;\n    [a,b] = [b,a];\n    console.log(a,b); // 9, 4\n\n    let arr =[1,2,3,4];\n    let [a,...b] = arr;\n    console.log(a); // 1 \n    console.log(b); // (3) [2, 3, 4]\n\n    let arr = [1];\n    let [a,b=0] = arr;\n    console.log(a,b); // 1 0    \n    \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 36. Spread Operator : Practical use\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n    const odd = [1,3,5];\n    const combined = [2,...odd, 4,6];\n    console.log(combined);   // [ 2, 1, 3, 5, 4, 6 ]\n    \n    1. Push an array inside another array\n      let rivers = ['Nile', 'Ganges', 'Yangte'];\n      let moreRivers = ['Danube', 'Amazon'];\n      rivers.push(...moreRivers);  // ['Nile', 'Ganges', 'Yangte', 'Danube', 'Amazon']\n  \n    2. Concatenate two or more arrays\n      let numbers = [1, 2];\n      let moreNumbers = [3, 4];\n      let allNumbers = [...numbers, ...moreNumbers];\n      console.log(allNumbers); // [1, 2, 3, 4]\n  \n    3. Copying an array\n      let scores = [80, 70, 90];\n      let copiedScores = [...scores];\n      console.log(copiedScores); // [80, 70, 90]\n    \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 37. Splice() method to delete existing elements, insert new elements, and replace elements in an array\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nThe splice() method is used to add or remove elements of an existing array \n```\n--------- Add element-----------\n  let colors = ['red', 'green', 'blue'];\n  colors.splice(2, 0, 'purple');\n  console.log(colors); ---------- (4) [\"red\", \"green\", \"purple\", \"blue\"]\n  colors.splice(1, 0, 'yellow', 'pink');\n  console.log(colors); ---------- (6) [\"red\", \"yellow\", \"pink\", \"green\", \"purple\", \"blue\"]\n\n--------- Remove element-----------\n  let arr = [4, 3, 5, 9];\n  arr.splice(2, 1);\n  console.log(arr); ---------- (3) [4, 3, 9]\n\n--------- Replacing elements-----------\n  let languages = ['C', 'C++', 'Java', 'JavaScript'];\n  languages.splice(1, 1, 'Python');\n  console.log(languages);  ---------- (4) [\"C\", \"Python\", \"Java\", \"JavaScript\"]\n  \n```\t    \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 38. Template Literals\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nTemplate literals are literals delimited with backtick ( ` ) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.\n\n```\n`string text`\n\n`string text line 1\n string text line 2`\n\n`string text ${expression} string text`\n\ntagFunction`string text ${expression} string text`\n\ntag`string text line 1 \\n string text line 2`;\n```\t    \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 39. ES6 template literals vs. concatenated strings\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nTemplate literals provide us with an alternative to string concatenation .They also allow us to insert variables in to a string. Template literals were introduced in ECMAScript 2015/ ES6 as a new feature. It provides an easy way to create multi-line strings and perform string interpolation.\n\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\nWhy would I use this new template literal method? I would recommend switching to the new format for a few reasons.\n\u003cbr\u003e\u003cbr\u003e\n  - One of which is that it requires fewer characters. So the extra space that you would need to use the plus before adds extra length to your code, causing it to look more bloated\n  - It no longer needs to escape single or double quotes. Yes, that’s right. You no longer need to put back slashes in order to close quotation marks.\n  - it’s much easier to read. With the dollar sign curly bracket syntax you can more clearly see what parts of your strings are using a variable.At a glance, I can quickly see that this is a variable.\n  - with my code editor, it would have improved syntax highlighting\n\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\n\nLet’s us rewrite our example from concatenated string:\n```\nConsole.log(\"Hello,welcome to\" +website.name+\"!\\\"message goes here\\\" \") ;\n```\n\u003cbr\u003e\u003cbr\u003e\nTo template literal:\n```\nConsole.log(`Hello,welcome to ${website.name} !\"message goes here\"` ) ;\n```\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 40. Write polyfill of Array.flat with customized nesting\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 41. There are two sorted arrays. Merge them in place of the first array\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\narr1 = [1, 2 , 3];\narr2 = [4, 5, 6];\narr1 = arr1.concat(arr2);\narr1 = [...arr1,...arr2];\n```\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 42. Write a js function that can be invoked like below -\ncalc().add(10).subtract(5).multiply(20).divide(2).getResult() . In this case, the output should be 50.\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 43. prototype chain -\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nThe prototype chain is a mechanism that allows objects to inherit properties and methods from other objects. Every object can have exactly one prototype object. That prototype object can also have a prototype object, and so on, creating a chain of inheritied properties and methods. The end of this chain is called the null prototype.\nEvery object in JavaScript can be linked to a prototype object which is the mechanism through which inheritance is provided.\nYou can see the prototype an object is pointing to using the __proto__ property.\n\n```\n// Define a human constructor\nfunction Person(name, age) {\n    this.name = name;\n    this.age = age;\n}\n\n// Add a method for greeting\nPerson.prototype.greet = function() {\n    console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old.`);\n};\n\n// Create a human instance\nconst person = new Person('John', 30);\n\n// Access the person's name attribute and output \"John\"\nconsole.log(person.name);\n\n// Access the greet method of person and output \"Hi, my name is John and I'm 30\"\nperson.greet()\n```\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 44. What is the first class function in JavaScript ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nA programming language is said to have First-class functions if functions in that language are treated like other variables. So the functions can be assigned to any other variable or passed as an argument or can be returned by another function. This means that functions are simply a value and are just another type of object.\n\n\u003cb\u003eUsage of First-Class Function\u003c/b\u003e\n  -  It can be stored as a value in a variable.\n  -  It can be returned by another function.\n  -  It can be passed into another function as an Argument.\n  -  It can also stored in an array, queue, or stack.\n  -  It can have its own methods and property.\n\n```\n  const Arithmetics = {\n    add: (a, b) =\u003e {\n        return `${a} + ${b} = ${a + b}`;\n    },\n    subtract: (a, b) =\u003e {\n        return `${a} - ${b} = ${a - b}`\n    },\n    multiply: (a, b) =\u003e {\n        return `${a} * ${b} = ${a * b}`\n    },\n    division: (a, b) =\u003e {\n        if (b != 0) return `${a} / ${b} = ${a / b}`;\n        return `Cannot Divide by Zero!!!`;\n    }\n\n}\n\nconsole.log(Arithmetics.add(100, 100));\nconsole.log(Arithmetics.subtract(100, 7))\nconsole.log(Arithmetics.multiply(5, 5))\nconsole.log(Arithmetics.division(100, 5));\n\n\nconst Geek = (a, b) =\u003e {\n    return (a + \" \" + b);\n}\n\nconsole.log(Geek(\"Akshit\", \"Saxena\"));\n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 45. What is a First Order Function in JavaScript ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nA First Order Function is just a normal regular function that does not take any function as one of its parameters and also it does not return another function as its return value inside its body. It is a simple function that accepts the parameters of different data types either primitive or non-primitive and it may or may not return a value as a result of the calculations performed on the passed parameters. A First Order Function can be declared using any of the methods available in JavaScript.\n\n```\nfunction firstOrderFunc(num1, num2){\n    console.log(num1*num2);\n}\nfirstOrderFunc(4, 35)\n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 45. What is Higher Order Function in JavaScript ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nA higher-order function is a function that can accept a function as one of its parameters and it can also return a function as its return value or it can do both return as well as accept a function. A higher-order function can also take as well as return other types of values but it either has to take a function as a parameter or return a function as its return value with them. It can be declared using any syntax available in JavaScript to declare functions.\n\n```\nfunction higherOrderFunc(a){\n    return function(b){\n        console.log(a*b)\n    }\n}\nhigherOrderFunc(3)(53);\n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 46. memoization in javascript\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nMemoization is a technique for speeding up applications by caching the results of expensive function calls and returning them when the same inputs are used again.\n\n\u003cb\u003eImportance of Memoization:\u003c/b\u003e When a function is given in input, it performs the necessary computation and saves the result in a cache before returning the value. If the same input is received again in the future, it will not be necessary to repeat the process. It would simply return the cached answer from the memory. This will result in a large reduction in a code’s execution time.\n\n\u003cb\u003eMemoization in Javascript:\u003c/b\u003e In JavaScript, the concept of memorization is based mostly on two ideas. They are as follows:\n  -  Closures\n  -  Higher-Order Functions\n\n```\n// Memoizer\nconst memoize = () =\u003e {\n \n    // Create cache for results\n    // Empty objects\n    const results = {};\n \n    // Return function which takes\n    // any number of arguments\n    return (...args) =\u003e {\n        // Create key for cache\n        const argsKey = JSON.stringify(args);\n \n        // Only execute func if no cached val\n        // If results object does not have \n        // anything to argsKey position\n        if (!results[argsKey]) {\n            results[argsKey] = func(...args)\n        }\n        return results[argsKey];\n    };\n};\n \n// Wrapping memoization function\nconst multiply = memoize((num1, num2) =\u003e {\n    let total = 0;\n    for (let i = 0; i \u003c num1; i++) {\n        for (let j = 0; j \u003c num1; j++) {\n \n            // Calculating square\n            total += 1 *;\n        }\n    }\n \n    // Multiplying square with num2\n    return total * num2;\n});\n \nconsole.log(multiply(500, 5000));\n```\nhttps://www.geeksforgeeks.org/how-to-write-a-simple-code-of-memoization-function-in-javascript/?ref=asr2\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 47. Dynamic object create ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\nfunction createObj(obj, field, value) {\n    if (Object.keys(obj).includes(field)) {\n        Object.assign(obj, {[field]: value});\n    } else {\n        obj[field] = value;\n    }\n    return obj;\n}\n\ncreateObj({}, 'one', 'value1')\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 48. Reduce operator examples\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\nconst arr =[[1,2], [3,4], [5,6]];\nconst finalArr = arr.reduce((accumulator, current)=\u003e accumulator.concat(current));\nconsole.log(finalArr); // (6) [1, 2, 3, 4, 5, 6]\n\nSum of numbers\n---------------------------------------------------------------\nconst numbers = [2, 4, 6, 8];\nconst result = numbers.reduce((accumulator, current)=\u003e accumulator + current);\nconsole.log(result); // 20\n\nAverage of numbers\n---------------------------------------------------------------\nconst numbers = [2, 4, 6, 8];\nconst result = numbers.reduce((accumulator, current, index, arr)=\u003e {\n\taccumulator+=current;\n    if(index === arr.length-1)  {\n    \treturn accumulator/arr.length;\n    }\n    return accumulator;\n});\nconsole.log(result); // 5\n\nAverage of numbers with initial value 100\n---------------------------------------------------------------\nconst numbers = [2, 4, 6, 8];\nconst result = numbers.reduce((accumulator, current, index, arr)=\u003e {\n\taccumulator+=current;\n    if(index === arr.length-1)  {\n    \treturn accumulator/arr.length;\n    }\n    return accumulator;\n}, 100);\nconsole.log(result); // 30\n\n ```\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 49. Arrow vs Normal functions ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n\u003cstrong\u003eAccess arguments\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\nIn regular functions, you can access all passed arguments using the arguments object, which is an array-like object containing each argument passed to the function.\n```\nfunction showArgs() {\n\tconsole.log(arguments);\n}\nshowArgs(1, 2, 3);  // [Arguments] { '0': 1, '1': 2, '2': 3 }\n```\nArrow functions do not have their own arguments object. To access arguments in arrow functions, use rest parameters (…args) to collect all arguments into an array.\n```\nconst showArgs = (...args) =\u003e {\n    console.log(args);\n};\nshowArgs(1, 2, 3);  // [ 1, 2, 3 ]\n```\n\n\u003cstrong\u003eDuplicate named parameters\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\nIn regular functions, duplicate named parameters are allowed but not recommended. The last occurrence of the parameter overwrites previous ones, and only its value is used.\n```\nfunction example(a, b, a) {\n    console.log(a, b);\n}\nexample(1, 2, 3); // 3 2\n```\n\nArrow functions do not allow duplicate named parameters, even in non-strict mode, and will throw a syntax error if duplicates are present. Always use unique parameter names in arrow functions.\n```\nconst example = (a, b, a) =\u003e {\n    console.log(a);\n}; \n// SyntaxError\n```\n\n\u003cstrong\u003eHosting\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\nIn regular functions, function declarations are hoisted to the top of their scope, allowing them to be called before they’re defined in the code.\n```\ngreet(); // Output: Hello Geeks!\n\nfunction greet() {\n    console.log('Hello Geeks!');\n}\n```\n\nArrow functions are not hoisted like regular function declarations. They are treated as variables, so they cannot be called before being defined due to the temporal dead zone.\n```\ngreet(); // ReferenceError: Cannot access 'greet' before initialization\n\nconst greet = () =\u003e {\n    console.log('Hello!');\n};\n```\n\n\u003cstrong\u003ethis keyword\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\nIn regular functions, this refers to the object that calls the function (runtime binding). Its value can vary based on how the function is called (method, event, or global).\n```\nconst obj = {\n    name: 'Geeks',\n    greet: function() {\n        console.log(this.name);\n    }\n};\nobj.greet();\n```\n\nIn arrow functions, this is lexically inherited from the surrounding scope, not the function itself.\n```\nconst obj = {\n    name: 'Geeks',\n    greet: () =\u003e {\n        console.log(this.name);\n    }\n};\nobj.greet(); // Output: undefined (inherited from outer scope)\n```\n\n\u003cstrong\u003enew keyword\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\nRegular functions can be used as constructors with the new keyword, allowing the creation of new object instances. The new keyword sets this to the new object inside the function.\n```\nfunction Person(name) {\n    this.name = name;\n}\n\nconst p = new Person('Geeks'); // Creates a new Person object\nconsole.log(p.name); // Geeks\n```\nArrow functions cannot be used as constructors and do not support the new keyword. Attempting to use new with an arrow function will result in a TypeError.\n```\nconst Person = () =\u003e {};\nconst p = new Person(); // TypeError: Person is not a constructor\n```\n  \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n\n### 50. Passing by Reference vs. Passing by Value ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n\n\u003cstrong\u003ePass by Reference or Call by Reference\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\nWhen a parameter is passed by reference, the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller's variable.\nPass by Reference will work with Non Primitive data types like arrays, objects, functions.\nInstead of making a copy, pass-by-reference does exactly what it sounds like; a value stored in memory gets referenced.\n\n```\nlet a = 5;\nlet b = a;\nconsole.log(a); // 5\nconsole.log(b); // 5\n\nb = a + 5;\nconsole.log(a); // 5\nconsole.log(b); // 10\n```\nboth variables a \u0026 b will work independently. \n\n\u003cstrong\u003ePass by Value or Call by Value\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\nWhen a parameter is passed by value, the caller and callee have two independent variables with the same value. If the callee modifies the parameter variable, the effect is not visible to the caller.\nPass by Value will work with Primitive data types like Boolean, char, byte, int, short, long, float, and double.\npass-by-value creates a new space in memory and makes a copy of a value, whereas pass-by-reference does not.\n\n```\nlet obj1 = { name: 'Piyali'};\nlet obj2 = obj1;\nconsole.log(obj1); // { name: 'Piyali'}\nconsole.log(obj2); // { name: 'Piyali'}\n\nobj2 = {name: 'Test'};\nconsole.log(obj1); // { name: 'Test'}\nconsole.log(obj2); // { name: 'Test'}\n```\nHere with let obj2 = obj1, we are giving reference of obj1 to obj2. So, any changes in value of obj2 will change the original value of obj1.\nSame thing will happen for array also.\n\n\u003cbr/\u003e Hindi Tutorial youtube link : https://www.youtube.com/watch?v=8y9c4SumvcQ\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 51. Remove Null and Undefined Values from an Object (Practical Coding)\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\nlet obj = {\n  a: 'test',\n  b: null,\n  c: undefined,\n  d: 'hi'\n};\n\nObject.entries(obj).filter(([key, value]) =\u003e value != null)\nprint in console -------------\n(2) [Array(2), Array(2)]\n0: (2) ['a', 'test']\n1: (2) ['d', 'hi']\n\nObject.fromEntries(Object.entries(obj).filter(([key, value]) =\u003e value != null))\nprint in console -------------\n{a: 'test', d: 'hi'}\n\n```\n\nWhy have written \"value != null\"?\nAns. The data type of undefined \u0026 null are not same. Data type of undefined is undefined. Data type of null is object. You can check using typeof operator.\n\nconsole.log(undefined == null) // true\nconsole.log(undefined === null) // false\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 52. Convert an Array to an Object\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n\n\u003cstrong\u003eSingle Dimention Array into an Object\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\n```\nObject.assign({}, ['a','b','c']);\n{0: 'a', 1: 'b', 2: 'c'}\n```\n\n\u003cstrong\u003eArray of Key-value pairs into an Object\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\n```\nlet a = [['JS', 'JavaScript'], ['GFG', 'GeeksforGeeks']];\nlet obj = Object.fromEntries(a);\n{ JS: 'JavaScript', GFG: 'GeeksforGeeks' }\n```\n\n\u003cstrong\u003eSpread Operator\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\n```\nconst arr = [\"Geeks\", \"for\", \"Geeks\"];\nconst obj = {...arr};\nconsole.log(obj); //  '0': 'Geeks', '1': 'for', '2': 'Geeks' }\n```\n\n\u003cstrong\u003eUsing forEach\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\n```\nconst arr = [\"Geeks\", \"for\", \"Geeks\"];\nconst obj = {};\narr.forEach((value, index) =\u003e obj[index] = value);\nconsole.log(obj); // { '0': 'Geeks', '1': 'for', '2': 'Geeks' }\n```\n\n\u003cstrong\u003eUsing Reduce\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\n```\nconst a = ['Hello', 'World', 'Welcome', 'To', 'JavaScript'];\n\nconst obj = a.reduce((acc, current, index) =\u003e {\n    acc[index] = current;\n    return acc;\n}, {});\n\nconsole.log(JSON.stringify(obj)); // {\"0\":\"Hello\",\"1\":\"World\",\"2\":\"Welcome\",\"3\":\"To\",\"4\":\"JavaScript\"}\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 53. Convert Map keys to an array\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n\u003cstrong\u003eUsing array.from() Method\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\n```\nlet myMap = new Map().set('GFG', 1).set('Geeks', 2);\nlet array = Array.from(myMap.keys());\nconsole.log(myMap.keys()); // MapIterator {'GFG', 'Geeks'}\nconsole.log(array); // (2) ['GFG', 'Geeks']\n```\n\n\u003cstrong\u003eUsing Object.keys() and Object.fromEntries()\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\n```\nconst myMap = new Map([\n    [\"JavaScript\", 1],\n    [\"Python\", 2],\n    [\"C++\", 3]\n]);\n\n// Convert Map to Object\nlet obj = Object.fromEntries(myMap); // {JavaScript: 1, Python: 2, C++: 3}\n\n// Extract keys from Object\nlet keysArray = Object.keys(obj);\n\nconsole.log(keysArray); // ['JavaScript', 'Python', 'C++']\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 54. How to serialize a Map in JavaScript ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nSerialization is the conversion of an object or a data structure to another format that is easily transferrable on the network.\n\n\u003cstrong\u003eUsing Array.from() and JSON.stringify() Method\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\n```\nconst map1 = new Map([\n    [1, 2],\n    [2, 3],\n    [4, 5]\n]);\n\nArray.from(map1); // Convert the map into an array using Array.from() method\n(3) [Array(2), Array(2), Array(2)]\n0: (2) [1, 2]\n1: (2) [2, 3]\n2: (2) [4, 5]\n\nJSON.stringify(Array.from(map1)) // Use the JSON.stringify() method on this converted array to serialize it.\n'[[1,2],[2,3],[4,5]]'\n\n```\n\n\u003cstrong\u003eUsing Object.fromEntries() and JSON.stringify() Method\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\n```\nconst map1 = new Map([\n    [1, 2],\n    [2, 3],\n    [4, 5]\n]);\n\nObject.fromEntries(map1); // Convert the map into an object using Object.fromEntries() method\n{1: 2, 2: 3, 4: 5}\n\nJSON.stringify(Object.fromEntries(map1)); // Use the JSON.stringify() method on this converted object to serialize it.\n'{\"1\":2,\"2\":3,\"4\":5}'\n```\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 55. Object vs JavaScript Map ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nA Map in JavaScript is a collection of key-value pairs where keys can be any data type. Unlike objects, keys in a Map maintain insertion order. It provides methods to set, get, delete, and iterate over elements efficiently, making it useful for data storage and retrieval tasks.\n\n\u003cstrong\u003eInsertion Order\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\nS6 Maps preserves the insertion order. A Map will keep the order of the inserted keys regardless of their type.\n```\nconst myData = new Map();\nmyData.set(10427, \"Description 10427\");\nmyData.set(10504, \"Description 10504\");\nmyData.set(10419, \"Description 10419\");\nconsole.log(myData); // Map(3) {10427 =\u003e 'Description 10427', 10504 =\u003e 'Description 10504', 10419 =\u003e 'Description 10419'}\n```\n\nconst obj = {};\nObject.assign(obj, {10427: \"Description 10427\"}); // {10427: 'Description 10427'}\nObject.assign(obj, {10504: \"Description 10504\"}); // {10427: 'Description 10427', 10504: 'Description 10504'}\nObject.assign(obj, {10419: \"Description 10419\"}); // {10419: 'Description 10419', 10427: 'Description 10427', 10504: 'Description 10504'}\n\n\u003cstrong\u003eKeys\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\nA Map 's keys can be any value (including functions, objects, or any primitive). A Map holds key-value pairs where the keys can be any datatype. Map has no restriction over key names. \nThe keys of an Object must be either a String or a Symbol.\n\n\u003cstrong\u003ePerforamce by memory heap\u003c/strong\u003e\n---------------------------------------------------------------------------------------------------------------------------------------------------\nThe V8 engine heap isn't very good at managing arrays of objects. If you have an array of 100,000 objects, loop through each object and delete one parameter in the middle then re-add it, the heap size will spike rather than stay constant.\n\n// Spike the memory heap\narr.forEach(obj =\u003e {let temp = obj[0]; delete obj[0]; obj[0] = temp})\nThe reason the heap will spike is because V8 creates intermediate arrays during the forEach loop over the array. Once the array you're looping over becomes massive (eg. 100,000 elements) the memory spike will be too large to handle and could crash the program.\n\nIterables like Map and Set aren't handled by the engine this way, and you can use a library like iter-tools to get array-like transformation methods for them.\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 56. Can we add Javascript function in JSON?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nhttps://www.geeksforgeeks.org/how-to-store-a-javascript-fnction-in-json/\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 57. Ho can add Dynamic key in Object?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\nlet tv = 'pCode', num = 10;\nlet obj = {\n    [tv]: 1001,\n    pName: 1000,\n    ['get' + num]() {\n        console.log(pName);\n    }\n}\n\nconsole.log(obj) ==============\n{pCode: 1001, pName: 1000, get10: ƒ}\nget10: ƒ ['get' + num]()\npCode: 1001\npName: 1000\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 58. What will the output of bellow ?\nfunction show() {\n    console.log(this);\n}\nshow();\n\nlet obj = {\n    display: function() {\n        console.log(this);\n    }\n}\nobj.display();\n\nlet obj = {\n    display: ()=\u003e {\n        console.log(this);\n    }\n}\nobj.display();\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\nfunction show() {\n    console.log(this);\n}\nshow(); // Window {0: global, window: Window, self: Window, document: document, name: '', location: Location, …}\n\nlet obj = {\n    display: function() {\n        console.log(this);\n    }\n}\nobj.display(); // {display: ƒ}\n\nlet obj = {\n    display: ()=\u003e {\n        console.log(this);\n    }\n}\nobj.display(); // Window {0: global, window: Window, self: Window, document: document, name: '', location: Location, …}\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 59. What Are Stack and Heap?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nStack: The Stack is used for static memory allocation, primarily for storing primitive types and function calls. It's a simple, last-in, first-out (LIFO) structure, making it very fast to access.\n\nHeap: The Heap is used for dynamic memory allocation, where objects and arrays (non-primitive types) are stored. Unlike the Stack, the Heap is more complex and slower to access, as it allows for flexible memory allocation.\n\n```\n---------------------------------------------------------------------------------------------\nExample of Stack Memory\n---------------------------------------------------------------------------------------------\nlet myYoutubeName = \"ayushyadavz\"; // Primitive type stored in the Stack.\nlet anotherName = myYoutubeName;   // A copy of the value is created in the Stack.\nanotherName = \"amanyadavz\";        // Changing the copy does not affect the original.\n\nconsole.log(myYoutubeName); // Output: ayushyadavz (Original value remains unchanged)\nconsole.log(anotherName);   // Output: amanyadavz (Only the copy value is changed)\n\n---------------------------------------------------------------------------------------------\nExample of Heap Memory\n---------------------------------------------------------------------------------------------\nlet userOne = {         // The reference to this object is stored in the Stack.\n    email: \"user@google.com\",\n    upi: \"user@ybl\"\n};                      // The actual object data is stored in the Heap.\n\nlet userTwo = userOne;  // userTwo references the same object in the Heap.\n\nuserTwo.email = \"ayush@google.com\"; // Modifying userTwo also affects userOne.\n\nconsole.log(userOne.email); // Output: ayush@google.com\nconsole.log(userTwo.email); // Output: ayush@google.com\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 60. What's the output of console.log(this) in JavaScript?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\nconsole.log(this);\n------------------------------------------------------------------------------------------------------\nWindow {0: global, window: Window, self: Window, document: document, name: '', location: Location, …}\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 61. Write a program using Promise and Async/Await.\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\nasync function fetchData() {\n  const response = await fetch(\"https://jsonplaceholder.typicode.com/posts/1\");\n  const data = await response.json();\n  console.log(data);\n}\n\nfetchData();\n------------------------------------------------------------------------------------------------------\n{\n  userId: 1,\n  id: 1,\n  title: ....',\n  body: ....}\n\n\nasync function fetchData() {\n  try {\n    let response = await fetch('https://api.example.com/data');\n    let data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\n```\n\nAdvantages of Async and Await\n------------------------------------------------------------------------------------------------------\nImproved Readability: Async and Await allow asynchronous code to be written in a synchronous style, making it easier to read and understand.\nError Handling: Using try/catch blocks with async/await simplifies error handling.\nAvoids Callback Hell: Async and Await prevent nested callbacks and complex promise chains, making the code more linear and readable.\nBetter Debugging: Debugging async/await code is more intuitive since it behaves similarly to synchronous code.\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 62. How would you efficiently handle 5000 records from an API call for a dropdown?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n \n\u003c/p\u003e\n\u003c/details\u003e\n\n### 62. How is Async/Await different from Promises?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nIn JavaScript, promises and async/await are two different ways to handle asynchronous operations. But they are closely related.\n\nPromise\n------------------------------------------------------------------------------------------------------\nA promise is an object that eventually leads to an asynchronous operation’s completion or failure. A promise can be in one of three states: pending, fulfilled, or rejected. When the asynchronous operation is completed, the Promise will either be fulfilled with a value or rejected with an error.\n\nAsync/Await\n------------------------------------------------------------------------------------------------------\nAsync/await is a syntactic sugar on top of promises. It provides a more concise way to write asynchronous code, making it easier to read and write. With Async/Await, you can write asynchronous code that looks similar to synchronous code, and it uses promises under the hood. In async/await, the async keyword is used to declare an asynchronous function. The await keyword is used to wait for a promise to be resolved before continuing with the execution of the function. The await keyword can only be used inside an async function.\n\nDifference\n------------------------------------------------------------------------------------------------------\nThe only difference is the execution context between promise and async/await.\nWhen a Promise is created and the asynchronous operation is started, the code after the Promise creation continues to execute synchronously. When the Promise is resolved or rejected, the attached callback function is added to the microtask queue. The microtask queue is processed after the current task has been completed but before the next task is processed from the task queue. This means that any code that follows the creation of the Promise will execute before the callback function attached to the Promise is executed.\nOn the other hand, with Async/Await, the await keyword causes the JavaScript engine to pause the execution of the async function until the Promise is resolved or rejected. While the async function waits for the Promise to resolve, it does not block the call stack, and any other synchronous code can be executed. Once the Promise is resolved, the execution of the async function resumes, and the result of the Promise is returned. If rejected, it throws an error value.\n\n------------------------------------------------------------------------------------------------------\nhttps://medium.com/version-1/difference-between-promise-and-async-await-95e453182f55\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 63. Explain Node.js and the Event Loop.\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nIn Node, the Event Loop is a mechanism that handles asynchronous operations. It allows Node to perform non-blocking I/O operations despite the fact that JavaScript is single-threaded. It continuously checks the call stack and message queue, executes tasks from stack processing asynchronous operations.\nhttps://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 64. How does this behave in Node.js? Is it the same as in the browser?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nIn Node. js all modules (script files) are executed in their own closure while browsers execute all script files directly within the global scope.\n\nIn the browser, running in the global scope, this is always window in your example\n```\nvar obj1;\nvar obj2;\n\nfunction x() {\n    obj1 = this; // window\n}\n\nfunction y() {\n    obj2 = this; // window\n}\n\nx();\ny();\n\nconsole.log(obj1 === obj2);  // window === window = true\nconsole.log(obj1 === this);  // window === window = true\n```\n\nThis is not how it works in Node. In Node.js all modules (script files) are executed in their own closure while browsers execute all script files directly within the global scope.\n\nIn other words, in just about any file running in Node, this will just be an empty object, as Node wraps the code in an anonymous function that is called immediately, and you'd access the global scope within that context with GLOBAL instead.\n\nHowever, when calling a function without a specific context in Node.js, it will normally be defaulted to the global object - The same GLOBAL mentioned earlier, as it's execution context.\n\nSo outside the functions, this is an empty object, as the code is wrapped in a function by Node, to create it's own execution context for every module (script file), while inside the functions, because they are called with no specified execution context, this is the Node GLOBAL object\n\nIn Node.js you'd get\n```\nvar obj1;\nvar obj2;\n\nfunction x() {\n    obj1 = this; // GLOBAL\n}\n\nfunction y() {\n    obj2 = this; // GLOBAL\n}\n\nx();\ny();\n\nconsole.log(obj1 === obj2);  // GLOBAL === GLOBAL = true\nconsole.log(obj1 === this);  // GLOBAL === {} = false\n```\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 65. Write code for mul(2)(3)(4) = 24.\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\nfunction mul(x) { \n      return function(y) { \n        return function(z) { \n          return x*y*z; \n        }; \n      } \n    } \n      \n    console.log(mul(2)(3)(5));  // 30\n    console.log(mul(2)(3)(4)); // 24\n```\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 66. Solution to 25 JavaScript interview questions.\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nhttps://medium.com/@dynamicsa420/solution-to-25-javascript-interview-questions-4162a1f76609\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 66. What is Axios ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nAxios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.\nhttps://axios-http.com/docs/intro\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 67. What is Axios ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nPrototype inheritance in javascript is the linking of prototypes of a parent object to a child object to share and utilize the properties of a parent class using a child class. Prototypes are hidden objects that are used to share the properties and methods of a parent class with child classes.\n\nThe syntax used for prototype inheritance has the proto property which is used to access the prototype of the child. The syntax to perform a prototype inheritance is as follows : \n```\nchild.__proto__ = parent;\n\n// Creating a parent object as a prototype\nconst parent = {\n  greet: function() {\n    console.log(`Hello from the parent`);\n  }\n};\n\n// Creating a child object\nconst child = {\n  name: 'Child Object'\n};\n\n// Performing prototype inheritance\nchild.__proto__ = parent;\n\n// Accessing the method from the parent prototype\nchild.greet(); // Outputs: Hello from the parent \n```\n\n```\n// Creating a prototype object\nconst personPrototype = {\n  introduce: function() {\n    console.log(`Hi, my name is ${this.name} and I am ${this.age} years old.`);\n  }\n};\n\n// Creating a new object that inherits from the personPrototype\nconst john = Object.create(personPrototype);\njohn.name = 'John';\njohn.age = 30;\n\n// Calling the introduce method on the john object\njohn.introduce(); \n// Outputs: Hi, my name is John and I am 30 years old.\n```\n\n```\n// Constructor function for creating Person objects\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n}\n\n// Creating an instance of the Person object\nconst person = new Person('John', 30);\n\n// Accessing the constructor property of the prototype\nconsole.log(person.constructor); \n// Outputs: ƒ Person(name, age) { this.name = name; this.age = age;}\n```\n\nThe prototype chain\n```\nlet student = {\n  id: 1,\n};\nlet tution = {\n  id: 2,\n};\nlet school = {\n  id: 3,\n};\nstudent.__proto__ = school; //level1 inheritance\nstudent.__proto__.__proto__ = tution; //level2 inheritance\nconsole.log(student.id); //the student object's property\nconsole.log(student.__proto__.id); //school object's property\n```\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 68. did you know that javascript behaves differently in the browser and in the Nodejs ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nNode.js and Web browsers are two different but interrelated technologies in web development. JavaScript is executed in both the environment, node.js, and browser but for different use cases. \n\nJavascript files loaded in Nodejs are automatically wrapped in anonymous functions.So in Node what you are really running is:\n```\n(function(/* There are args here, but they aren't important for this answer */){\n  var x = 10;\n  var o = { x: 15 };\n  function f(){\n    console.log(this.x);\n  }\n  f();\n  f.call(o);\n})();\n```\n\nThe environment of both Node.js and Browser are very different due to their different purpose Some key differences are:\n\nThe browser executes JavaScript within the Host Environment, on the client side. Browsers provide a Document Object Model(DOM) which represents the structure of web pages.\nNode.js provides a runtime environment that allows JavaScript to run on a server, outside the browser. Also, it does not have a DOM like web browsers.\n\n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 69. What is the difference between `==` and `===`?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nThe “===” operator compares both content and type, whereas “==” compares only content. The == operator will compare for equality after doing any necessary type conversions. The === operator will not do type conversion, so if two values are not the same type === will simply return false .\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 70. How do you handle errors in JavaScript?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nError handling in JavaScript plays an important role to make the application stable. Structures such as try-catch blocks, throw statement and finally block are used to deal with unexpected situations and ensure that the application runs correctly.\n\n```\ntry {\n    console.log(\"try block: The code is running...\");\n} catch (error) {\n    console.log(\"Error Caught: \" + error);\n} finally {\n    console.log(\"finally block: Executed in all cases.\");\n}\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 71. What is globalThis ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nglobalThis aims to consolidate the increasingly fragmented ways of accessing the global object by defining a standard global property. The globalThis proposal is currently at stage 4, which means it’s ready for inclusion in the ES2020 standard. All popular browsers, including Chrome 71+, Firefox 65+, and Safari 12.1+, already support the feature. You can also use it in Node.js 12+.\n\n// browser environment\nconsole.log(globalThis);    // =\u003e Window {...}\n\n// node.js environment\nconsole.log(globalThis);    // =\u003e Object [global] {...}\n\n// web worker environment\nconsole.log(globalThis);    // =\u003e DedicatedWorkerGlobalScope {...}\nBy using globalThis, your code will work in window and non-window contexts without having to write additional checks or tests. In most environments, globalThis directly refers to the global object of that environment. In browsers, however, a proxy is used internally to take into account iframe and cross-window security. In practice, it doesn’t change the way you write your code, though.\n\nGenerally, when you’re not sure in what environment your code will be used, or when you want to make your code executable in different environments, the globalThis property comes in very handy. You’ll have to use a polyfill to implement the feature on older browsers that do not support it, however.\n\nOn the other hand, if you’re certain what environment your code is going to be used in, then use one of the existing ways of referencing the environment’s global object and save yourself from the need to include a polyfill for globalThis.\n\nhttps://blog.logrocket.com/what-is-globalthis-why-use-it/\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 72. What is debouncing and throttling in JavaScript?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nExecution Frequency: Debouncing postpones the execution until after a period of inactivity, while throttling limits the execution to a fixed number of times over an interval.\nUse Cases: Debouncing is ideal for tasks that don’t need to execute repeatedly in quick succession, such as API calls based on user input. Throttling is suited for controlling the execution rate of functions called in response to events like scrolling or resizing.\n\nDebouncing and throttling are powerful techniques for optimizing JavaScript applications, preventing unnecessary code executions, and improving user experience.\n\nDebouncing Usecase :\nConsider a search input field that fetches suggestions from a server as the user types. Without debouncing, every keystroke would send a request, potentially leading to hundreds of requests per minute. Debouncing allows us to delay the function call until the user has stopped typing for a predefined time.\n```\nfunction debounce(func, delay) {\n  let debounceTimer;\n  return function() {\n    const context = this;\n    const args = arguments;\n    clearTimeout(debounceTimer);\n    debounceTimer = setTimeout(() =\u003e func.apply(context, args), delay);\n  };\n}\n// Usage\nconst fetchSuggestions = debounce(() =\u003e {\n  // Fetch suggestions from the server\n}, 250);\n```\n\nThrottling Usecase :\nAn example use case is attaching a listener to the scroll event of a webpage. Since the scroll event can fire dozens of times per second, throttling can be used to limit the number of times your callback function executes, improving performance.\n```\nfunction throttle(func, limit) {\n  let inThrottle;\n  return function() {\n    const args = arguments;\n    const context = this;\n    if (!inThrottle) {\n      func.apply(context, args);\n      inThrottle = true;\n      setTimeout(() =\u003e (inThrottle = false), limit);\n    }\n  };\n}\n// Usage\nwindow.addEventListener('scroll', throttle(() =\u003e {\n  // Handle the scroll event\n}, 1000));\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 73. How would you implement a deep clone of an object without using libraries?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nUsing Spread Operator to Deep Clone\n```\nlet student1 = {\n    name: \"Manish\",\n    company: \"Gfg\"\n}\n\nlet student2 = { ...student1 };\n\nstudent1.name = \"Rakesh\"\n\nconsole.log(\"student 1 name is\", student1.name); // student 1 name is Rakesh\nconsole.log(\"student 2 name is \", student2.name); // student 2 name is  Manish\n```\n\nUsing Object.assign() Method\n```\nlet student1 = {\n    name: \"Manish\",\n    company: \"Gfg\"\n}\nlet student2 = Object.assign({}, student1);\n\nstudent1.name = \"Rakesh\"\n\nconsole.log(\"student 1 name is\", student1.name); // student 1 name is Rakesh\nconsole.log(\"student 2 name is \", student2.name); // student 2 name is  Manish\n```\n\nUsing Json.parse() and Json.stringify() Methods\n```\nlet student1 = {\n    name: \"Manish\",\n    company: \"Gfg\"\n\n}\nlet student2 = JSON.parse(JSON.stringify(student1))\n\nstudent1.name = \"Rakesh\"\n\nconsole.log(\"student 1 name is\", student1.name); // student 1 name is Rakesh\nconsole.log(\"student 2 name is \", student2.name); // student 2 name is  Manish\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 74. Event Delegation in JavaScript ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nEvent 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.\n\nLet’s see an example with and without event delegation\n```\nconst customUI = document.createElement('ul');\n\nfor (var i = 1; i \u003c= 10; i++) {\n    const newElement = document.createElement('li');\n    newElement.textContent = \"This is line \" + i;\n    newElement.addEventListener('click', () =\u003e {\n        console.log('Responding')\n    })\n    customUI.appendChild(newElement);\n}\n```\nThe above code will associate the function with every \u003cli\u003e element that is shown in the below image. We are creating an \u003cul\u003e element, attaching too many \u003cli\u003e elements, and attaching an event listener with a responding function to each paragraph as we create it.\n\n\nWithout Event Delegation\n\nImplementing the same functionalities with an alternate approach. In this approach, we will associate the same function with all event listeners. We are creating too many responding functions (that all actually do the exact same thing). We could extract this function and just reference the function instead of creating too many functions:\n```\nconst customUI = document.createElement('ul');\n\nfunction responding() {\n    console.log('Responding')\n}\n\nfor (var i = 1; i \u003c= 10; i++) {\n    const newElement = document.createElement('li');\n    newElement.textContent = \"This is line \" + i;\n    newElement.addEventListener('click', responding)\n    customUI.appendChild(newElement);\n}\n```\nThe functionality of the above code is shown below –\n\n\nWithout Event Delegation\n\nIn the above approach, we still have too many event listeners pointing to the same function. Now implementing the same functionalities using a single function and single event.\n```\nconst customUI = document.createElement('ul');\n\nfunction responding() {\n    console.log('Responding')\n}\n\nfor (var i = 1; i \u003c= 10; i++) {\n    const newElement = document.createElement('li');\n    newElement.textContent = \"This is line \" + i;\n    customUI.appendChild(newElement);\n}\ncustomUI.addEventListener('click', responding)\n```\n\nNow there is a single event listener and a single responding function. In the above-shown method, we have improved the performance, but we have lost access to individual \u003cli\u003e elements so to resolve this issue, we will use a technique called event delegation. \n \n\u003c/p\u003e\n\u003c/details\u003e\n\nhttps://www.geeksforgeeks.org/event-delegation-in-javascript/\n---\n\n### 75. What are the microtask and macrotask within an event loop in JavaScript ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\n\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 76. Implement a chain calculator\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\nconst calculator = {\n  total: 0,\n  add: function(val){\n    this.total += val;\n    return this;\n  },\n  subtract: function(val){\n    this.total -= val;\n    return this;\n  },\n  divide: function(val){\n    this.total /= val;\n    return this;\n  },\n  multiply: function(val){\n    this.total *= val;\n    return this;\n  }\n};\n\ncalculator.add(10).subtract(2).divide(2).multiply(5);\nconsole.log(calculator.total); // 20\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 77. Execute promises in sequence ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nIn JavaScript, executing multiple promises sequentially refers to running asynchronous tasks in a specific order, ensuring each task is completed before the next begins. This is essential when tasks depend on the results of previous ones, ensuring correct flow and preventing unexpected behavior.\n```\nlet promise1 = new Promise((resolve, reject) =\u003e {\n    // Resolves immediately with \"Hello! \"\n    resolve(\"Hello! \");\n});\n\nlet promise2 = new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e {\n        // Resolves after 1 second with \"GeeksforGeeks\"\n        resolve(\"GeeksforGeeks\");\n    }, 1000);\n});\n\n// Chain the promises to execute sequentially\npromise1.then((result1) =\u003e {\n    // Logs result from promise1\n    console.log(result1);\n    // Returns promise2 to chain\n    return promise2;\n}).then((result2) =\u003e {\n    // Logs result from promise2\n    console.log(result2);\n});\n```\n\nThe for…of loop with async-await in JavaScript allows you to execute promises sequentially. It iterates over an array of promises, awaiting each promise’s resolution before moving to the next, ensuring proper sequential execution of asynchronous tasks.\n```\n// Promise 1 that resolves immediately\nlet promise1 = new Promise((resolve, reject) =\u003e {\n    resolve(\"Hello! \");\n});\n\n// Promise 2 that resolves after a 1-second delay\nlet promise2 = new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e {\n        resolve(\"GeeksforGeeks\");\n    }, 1000);\n});\n\nlet promiseExecution = async () =\u003e {\n    // Iterates over an array of promises and awaits each one sequentially\n    for (let promise of [promise1, promise2]) {\n        try {\n            // Waits for each promise to resolve\n            const message = await promise;\n            console.log(message); \n             // Logs the resolved value\n        } catch (error) {\n        // Catches and logs any errors\n            console.log(error.message);  \n        }\n    }\n};\npromiseExecution();\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 78. Implement pipe and compose functions ?\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nThe compose() function is used to combine multiple functions into a single function. It takes a series of functions as arguments and returns a new function that, when executed, runs the original functions from right to left. This means the output of the rightmost function is passed as the input to the next function, and so on.\n```\nconst compose = (...fns) =\u003e (input) =\u003e fns.reduceRight((chain, func) =\u003e func(chain), input);\nconst sum = (...args) =\u003e args.flat(1).reduce((x, y) =\u003e x + y);\nconst square = (val) =\u003e val*val; \ncompose(square, sum)([3, 5]); // 64\n```\nUses of Compose()\n------------------------\nWhen the sequence of transformations starts with the final result in mind.\nCommon in middleware composition (e.g., Redux).\nUseful in functional programming to build complex operations from simple functions.\n\nThe pipe() function is similar to compose(), but it combines functions from left to right. This means the output of the leftmost function is passed as the input to the next function, and so on. It’s essentially the same as compose(), but the order of function execution is reversed.\n```\nconst pipe = (...fns) =\u003e (input) =\u003e fns.reduce((chain, func) =\u003e func(chain), input);\nconst sum = (...args) =\u003e args.flat(1).reduce((x, y) =\u003e x + y);\nconst square = (val) =\u003e val*val; \npipe(sum, square)([3, 5]); // 64\n```\nUses of pipe()\n------------------------\nWhen the sequence of transformations starts from the initial input and flows to the final result.\nCommon in data processing pipelines.\nPreferred in scenarios where readability and straightforward function chaining are important.\n\nTo make it short, composition and piping are almost the same, the only difference being the execution order; If the functions are executed from left to right, it's a pipe, on the other hand, if the functions are executed from right to left it's called compose.\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 79. Create custom array polyfills\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nA polyfill is code that implements a feature on web browsers that do not support the feature.\n\nPolyfill of forEach() method.\n----------------------------------------------------------------------\nArray.prototype.myForEach = function(callback){\n    for(let i=0; i\u003cthis.length; i++){\n      callback(this[i],i,this)\n    }\n}\n\nPolyfill of map() method.\n----------------------------------------------------------------------\nArray.prototype.myMap = function(callback){\n    const arr = [];\n    for(let i=0; i\u003cthis.length; i++){\n       arr.push(callback(this[i],i,this));\n     }\n     return arr;\n}\n\nPolyfill of filter() method.\n----------------------------------------------------------------------\nArray.prototype.myFilter = function(callback){\n    const arr = [];\n    for(let i=0; i\u003cthis.length; i++){\n       if(callback(this[i],i,this)){\n            arr.push(this[i]);\n       }\n    }\n    return arr;\n}\n\nPolyfill of find() method.\n----------------------------------------------------------------------\nArray.prototype.myFind = function(callback){\n    for(let i=0; i\u003cthis.length; i++){\n      const res = callback(this[i],i,this);\n        if(res){\n          return this[i];\n        }\n     }\n     return undefined;\n}\n\nPolyfill of reduce() method\n----------------------------------------------------------------------\nArray.prototype.myReduce=function(){\n   const callback = arguments[0];\n   let currentVal = arguments[1];\n   for(let i=0; i\u003cthis.length; i++){\n     let result = callback(currentVal, this[i], i ,this); \n        currentVal = result;\n   }\n   return currentVal;\n}\nvar logicAlbums = [ ‘Bobby Tarantino’, ‘The Incredible True Story’, ‘Supermarket’, ‘Under Pressure’, ]\nvar withReduce = logicAlbums.myReduc(function(a, b) { return a + ‘ , ‘ + b}, ‘Young Sinatra’)\n\nPolyfill of every() method\n----------------------------------------------------------------------\nArray.prototype.myEvery = function(callback){\n   for(let i=0; i\u003cthis.length; i++){\n     if(!callback(this[i],i,this)){\n       return false;\n     }\n   }\n   return true;\n}\n\nPolyfill of some() method\n----------------------------------------------------------------------\nArray.prototype.mySome = function(callback){\n   for(let i=0; i\u003cthis.length; i++){\n     if(callback(this[i],i,this)){\n       return true;\n     }\n   }\n   return false;\n}\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 80. Flatten a nested array\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\nconst arr1 = [0, 1, 2, [3, 4]];\n\nconsole.log(arr1.flat());\n// expected output: Array [0, 1, 2, 3, 4]\n\nconst arr2 = [0, 1, [2, [3, [4, 5]]]];\n\nconsole.log(arr2.flat());\n// expected output: Array [0, 1, 2, Array [3, Array [4, 5]]]\n\nconsole.log(arr2.flat(2));\n// expected output: Array [0, 1, 2, 3, Array [4, 5]]\n\nconsole.log(arr2.flat(Infinity));\n// expected output: Array [0, 1, 2, 3, 4, 5]\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 81. Build an event emitter\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \n```\n\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 82. Create a debouncing function with leading and trailing calls\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nDebouncing is a technique that is used in programming to reduce the function invocation.\n\nIt runs with the assumption that rather than invoking the functions on every action, allows the user to complete their thought process and invoke the function only after a certain buffer between two actions.\n\nFor example, if the user is typing something in the search box, rather than making a network request on every word that the user types, we should allow the user to finish typing and only when he stops for X amount of time, the function to make a network request should be invoked.\n\nIt is one of the classic frontend interview questions, but because the classic debounce has been common, nowadays its variation is asked during interviews like debounce with immediate flag.\n\nThis is another variation of debounce in which we have to use the trailing and leading options.\n\nIf trailing is enabled, the debounce will invoke after the delay just like classic implementation. If leading is enabled, it will invoke at the beginning. If both are enabled then it will invoke twice at the beginning and after the delay.\n```\nconst debounce = (fn, delay, option = { leading: true, trailing: true}) =\u003e {\n  let timeout;\n  let isLeadingInvoked = false;\n  \n  return function (...args) {\n    const context = this;\n    \n    //base condition\n    if(timeout){\n      clearTimeout(timeout);\n    }\n    \n    // handle leading\n    if(option.leading \u0026\u0026 !timeout){\n      fn.apply(context, args);\n      isLeadingInvoked = true;\n    }else{\n      isLeadingInvoked = false;\n    }\n    \n    // handle trailing\n    timeout = setTimeout(() =\u003e {\n      if(option.trailing \u0026\u0026 !isLeadingInvoked){\n        fn.apply(context, args);\n      }\n      \n      timeout = null;\n    }, delay);\n  }\n}\n```\n\n```\nconst onChange = (e) =\u003e {\n  console.log(e.target.value);\n}\nconst debouncedSearch = debounce(onChange, 1000);\nconst input = document.getElementById(\"search\");\ninput.addEventListener('keyup', debouncedSearch);\n```\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 83. Implement MapLimit functionality\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nhttps://learnersbucket.com/examples/interview/implement-maplimit-async-function/#:~:text=Implement%20a%20mapLimit%20function%20that,can%20occur%20at%20a%20time.\n \n\u003c/p\u003e\n\u003c/details\u003e\n\n---\n\n### 84. Create a cancelable promise\n\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003eAnswer\u003c/b\u003e\u003c/summary\u003e\n\u003cp\u003e\n\n#### \nPromises once fired, cannot be cancelled. So cancelling the promises in our curr","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpiyalidas10%2Fjavascript-interview-questions-mylists","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpiyalidas10%2Fjavascript-interview-questions-mylists","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpiyalidas10%2Fjavascript-interview-questions-mylists/lists"}