{"id":24813710,"url":"https://github.com/rabi-siddique/js-interview-questions","last_synced_at":"2025-03-25T18:23:31.984Z","repository":{"id":224701181,"uuid":"745962686","full_name":"rabi-siddique/js-interview-questions","owner":"rabi-siddique","description":"A list of JS interview questions. ","archived":false,"fork":false,"pushed_at":"2024-02-16T17:18:47.000Z","size":10,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-01-30T15:51:44.763Z","etag":null,"topics":["coding","javascript","javascript-interview-questions","programming"],"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/rabi-siddique.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}},"created_at":"2024-01-20T17:15:14.000Z","updated_at":"2024-11-16T11:30:31.000Z","dependencies_parsed_at":"2024-02-27T11:01:14.798Z","dependency_job_id":"d5136fa9-ad70-4a57-8895-37e34a9483b3","html_url":"https://github.com/rabi-siddique/js-interview-questions","commit_stats":null,"previous_names":["rabi-siddique/js-interview-questions"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rabi-siddique%2Fjs-interview-questions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rabi-siddique%2Fjs-interview-questions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rabi-siddique%2Fjs-interview-questions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rabi-siddique%2Fjs-interview-questions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rabi-siddique","download_url":"https://codeload.github.com/rabi-siddique/js-interview-questions/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245517597,"owners_count":20628371,"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":["coding","javascript","javascript-interview-questions","programming"],"created_at":"2025-01-30T15:51:49.238Z","updated_at":"2025-03-25T18:23:31.952Z","avatar_url":"https://github.com/rabi-siddique.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Scopes and Closures\n\n## Scopes\n\nScope is like a look up list for variables. It enforces a set of rules related to the accessibility of these variables for the currently executing code.\n\nWhen JavaScript code is being compiled, variables are allocated memory. However when execution of code happens, the variable assignments are performed.\n\nConsider this code:\n\n```js\nvar a = 2;\n```\n\nIn compilation, `a` is allocated memory. In exection, JS Engine finds `a` in the current scope. If it is present there, it will assign the value `2` to it. If its not found, JS Engine will look for the variable in the outercontaining scopes. The process of looking in the outercontaining scopes is continued until the global scope is reached.\n\nIf the variable is not found in global scope, a `Reference Error` is thrown, if we are in `strict mode`. However, in `non-strict mode`, the variable is created in the global scope.\n\nAbout the errors, the `Reference Error` is related to scopes. If scope resolution fails for a variable, we will encounter this error. On the other hand, with `Type Error`, scope resolution was successful. But we are trying to perform some illegal operation on the result of scope resolution. For example, invoking a primitive as a function, trying to reference a property on an `undefined` or `null` value.\n\nLexical Scope is the scope that is defined at lexing time. No matter where a function is invoked from or how it is invoked, its lexical scope is always defined by where the function was declared. To cheat the lexical scope at runtime:\n\n- eval funcion\n- with\n\n## Closures\n\nA closure is mechanism through which a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope.\n\nWhen a function is called in JavaScript, a new local memory, also known as a variable environment or state, is created for that function's execution context. This local memory stores the function's variables parameters, and references to any variables from outer scopes that the function needs. After the function completes its execution, its local memory is typically deleted or garbage-collected, except for the returned value (if any).\n\nClosures allow functions to retain access to variables from the outercontaining scopes even after the outer function has finished executing. This means that a function returned from another function (creating a closure) can still access and manipulate the variables of its parent function, even if the parent function's local memory was deleted.\n\nThis allows for powerful patterns like encapsulation, data hiding, and maintaining state across function calls.\n\n## What are Scopes in JavaScript?\n\nScopes are sections of our code where a variable is defined and can be accessed.\n\nThere are 4 main types of Scopes in JavaScript:\n\n- **Global Scope**: All variables are visible to the entire program.\n- **Function Scope**: All variables are visible inside of a function.\n- **Block Scope**: All variables are visible inside of a block.\n- **Module Scope**: All variables are visible within the module.\n\nThere are three factors that determine the scope of a variable:\n\n- How is it was declared? i.e. Using `let`, `const`, `var`, `function expression`, `function declaration` etc.\n- Where it was declared? i.e. `Function`, `Class`, `Block` etc.\n- Are we in strict mode or non strict mode.\n\n## What is Lexical Scope?\n\nScopes are determined at compile time. And at compile time it is determined by examining the location where the function is declared. Lexical scope means that no matter where a function is invoked from or how it is invoked, its lexical scope is always defined by where the function was declared.\n\nIn other words, lexical scope refers to the ability of a function scope to access variables from the parent scope. When there is lexical scope, the innermost and outermost functions may access all variables from their parent scopes all the way up to the global scope.\n\n## How does JavaScript implicitly declare variables, and what impact does the use of strict mode have on this behavior?\n\nConsider this piece of code:\n\n```js\nvar a = b;\n```\n\nIn this piece of code, when JS engine encounters the line of code, it will search for the variable `b` in the scope chain. It starts searching for `b` in the currently executing scope. If it's not found there, the searching is shifted to the scopes outside the currently executing scopes. This process of searching keeps on running scope by scope, until we reach the global scope. And when it is not found, JavaScript implicitly creates `b` in the global scope.\n\nHowever, if we were in `strict mode`, this won't happen. In that case, a `ReferenceError` is produced.\n\n## What is Shadowing in JavaScript?\n\nIn nested scopes, we can have variables with the same name. In that case, JS engine stops searching for the variable upon finding the first match. This is called Shadowing in JavaScript.\n\nA thing to note here is that in JavaScript, variables in the global scope are part of the window object. So if we were to access these variables in a lexical scope, we can use `window.variableName`. This way we can access variables declared in global scope that would have been otherwise inaccessbile due to shadowing. However, its important to note, that non-global shadowed variables can't be accessed.\n\n## What is the importance of Scopes?\n\nScopes are important because:\n\n- **Avoiding Variable Name Collisions**: Different parts of a program might use the same variable names for different purposes. By using scopes, you can create local variables that are only accessible within a specific scope, preventing unintentional collisions with variables in other parts of the program. This helps in maintaining code integrity and readability.\n\n- **Encapsulation**: Scopes contribute to the concept of encapsulation, where the internal details of a function or block of code are hidden from the outside world. This is important in preventing unintended data corruption or unauthorized access.\n\n## What are Closures in JavaScript?\n\nClosures in JavaScript is a concept which allows a function to gain access to all the variables declared outside of its own scope. A function bundled with the surrounding scopes forms a closure. Now this is powerful because it let our function definitions have an associated cache/persistent memory.\n\nClosure acts as a permanent memory for the function. The local memory of the function is deleted when the function execution is completed. However, the closure which is like a backpack of data, is permanent. It persists in subsequent function calls.\n\nThe closrue contains all the variables used by the function. The variables not used inside the function are not linked to its closure. JavaScript does this optimization for us. JavaScript Engine sees inside the function definition to get an idea of what variables are being used by it. It then adds only the variable used inside the function definition to the closure.\n\nThe key thing to remember is that when a function gets declared, it contains a function definition and a closure.\n\n## What are the benefits of closures?\n\n- **Encapsulation**: Closures allow for the creation of private variables and functions. Variables within a closure are not directly accessible from the outside, helping to maintain the integrity and security of the data.\n\n- **Maintaining State**: Closures enable the creation of functions that can maintain and update their internal state across multiple invocations. This is particularly useful for scenarios where you need to keep track of some information between function calls without exposing it globally.\n\n- **Module Pattern**: Closures are instrumental in implementing the module pattern in JavaScript. By creating a function that returns an object containing methods and variables, you can simulate private and public members, achieving a level of organization and encapsulation.\n\n```js\nfunction myModule() {\n  // Private variables and functions\n  var privateVar = 'I am private';\n\n  function privateFunction() {\n    console.log('This is a private function');\n  }\n\n  // Public API (methods and variables accessible from the outside)\n  return {\n    // Public variables\n    publicVar: 'I am public',\n\n    // Public function\n    publicFunction: function () {\n      console.log('This is a public function');\n      // It can access private variables and functions\n      console.log(privateVar);\n      privateFunction();\n    },\n  };\n}\n```\n\n- **Factory Functions**: Closures are often used in the creation of factory functions. These functions produce and return other functions with specific behaviors or configurations based on the arguments provided. This allows for the creation of reusable and customizable code.\n\n```js\nfunction createMathOperation(operationType) {\n  return function (operand1, operand2) {\n    switch (operationType) {\n      case 'add':\n        return operand1 + operand2;\n      case 'subtract':\n        return operand1 - operand2;\n      case 'multiply':\n        return operand1 * operand2;\n      case 'divide':\n        return operand1 / operand2;\n      default:\n        throw new Error('Invalid operation type');\n    }\n  };\n}\n\n// Create specific math operation functions using the factory\nvar addFunction = createMathOperation('add');\nvar subtractFunction = createMathOperation('subtract');\nvar multiplyFunction = createMathOperation('multiply');\nvar divideFunction = createMathOperation('divide');\n\n// Use the created functions\nconsole.log(addFunction(5, 3)); // Output: 8\nconsole.log(subtractFunction(8, 2)); // Output: 6\nconsole.log(multiplyFunction(4, 6)); // Output: 24\nconsole.log(divideFunction(10, 2)); // Output: 5\n```\n\n## Read More Sources\n\n- [Scopes of Variables](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript#:~:text=Javascript%20uses%20scope%20chains%20to,linked%20to%20the%20outer%20function.)\n- [UnderStanding Scope and Scope Chain in JavaScript](https://blog.bitsrc.io/understanding-scope-and-scope-chain-in-javascript-f6637978cf53#:~:text=JavaScript%20uses%20lexical%20scope%20which,every%20JavaScript%20developer%20should%20understand.)\n- [Closures](https://medium.com/dailyjs/i-never-understood-javascript-closures-9663703368e8)\n\n# Promises\n\n## What is a Promise?\n\nA promise is a JavaScript object which will produce a single value some time in the future. It is a mechanism to perform async operations in JavaScript. It has three states. These are:\n\n- `Pending`: Starting state of every promise, neither fulfilled nor rejected.\n- `Fulfilled`: The operation completed successfully.\n- `Rejected`: The operation failed.\n\nIf the promise is successful, it will produce a resolved value, but if something goes wrong then it will produce a reason why the promise was rejected.\n\nAfter the promise is resolved or rejected, the following handler methods which take callbacks as arguments are called:\n\n- `then`: When the promise is resolved the callback argument of this function will be called.\n- `catch`: When the promise is rejected the callback argument of this function will be called.\n\n## Explain the difference between Promise and Callback functions.\n\nBoth promises and callbacks are used to handle async operations in JavaScript.\n\nCallbacks are functions passed as arguments to other functions, and they are executed after the completion of a certain asynchronous operation or event. Commonly used in event handling, AJAX requests, and other asynchronous tasks.\n\nOn the other hand, Promises are JavaScript objects that return a value sometime in the future. A promise after being resolved/rejected, will use `then` and `catch` handlers which take callbacks as arguments. They provide a cleaner way to handle async code compared to callbacks.\n\n## How can you create a Promise that resolves after a specific time delay?\n\nYou can use the setTimeout function to create a delay and resolve the Promise after that delay. For example:\n\n```js\nconst delay = (ms) =\u003e new Promise((resolve) =\u003e setTimeout(resolve, ms));\n```\n\n## What is the purpose of the Promise.all method?\n\nPromise.all takes an array of promises as input and returns a single Promise that fulfills with an array of the fulfilled values when all of the input promises have been fulfilled. If any of the input promises is rejected, the whole Promise.all is rejected.\n\n## Why forEach loops are not good for async operations?\n\n`forEach` is not designed for asynchronous code. Consider this code:\n\n```js\nconst players = await this.getWinners();\n\nawait players.forEach(async (player) =\u003e {\n  await givePrizeToPlayer(player);\n});\n```\n\nThe promises returned by the iterator function are not handled. So if one of them throws an error, the error won't be caught. Also, forEach does not wait for each promise to resolve, all the promises are awarded in parallel, not serial.\n\n## Describe some practical use cases of Promises\n\n- `Fetching Data from APIs`: When making HTTP requests to APIs to fetch data, promises are commonly used to handle the asynchronous nature of network requests. Libraries like Axios or Fetch API return promises, allowing you to handle the response or error once the request is complete.\n\n```js\nfetch('https://api.rabi.com/data')\n  .then((response) =\u003e response.json())\n  .then((data) =\u003e {\n    // Handle the fetched data\n  })\n  .catch((error) =\u003e {\n    // Handle errors\n  });\n```\n\n- `Handling File Operations`: When reading or writing files asynchronously, promises can be used to handle the completion or failure of these operations. \n\n```js\nconst fs = require('fs').promises;\n\nfs.readFile('file.txt', 'utf-8')\n  .then((data) =\u003e {\n    // Handle the file data\n  })\n  .catch((error) =\u003e {\n    // Handle errors\n  });\n```\n\n- `Async Functions`: Promises are often used with async/await syntax, which provides a cleaner way to write asynchronous code. Async functions return promises implicitly, allowing you to write asynchronous code in a synchronous-like manner.\n\n```js\nasync function fetchData() {\n  try {\n    const response = await fetch('https://api.rabi.com/data');\n    const data = await response.json();\n    // Handle the fetched data\n  } catch (error) {\n    // Handle errors\n  }\n}\n```\n\n- `Delays:`Promises can be useful to implement delays in your code.\n\n```js\nfunction delay(ms) {\n  return new Promise((resolve) =\u003e setTimeout(resolve, ms));\n}\n\ndelay(6000).then(() =\u003e {\n  console.log('After 6 seconds');\n});\n```\n\n- `Parallel Tasks`: Imagine you have two tasks that can be done at the same time, like fetching your user info and your posts from a website. You don't want to wait for one to finish before starting the other. Promises can handle this using `Promise.all`.\n\n```js\nconst userId = 234;\n\nfunction fetchUserData(userId) {\n  return fetch(`https://api.rabi.com/users/${userId}`).then((response) =\u003e\n    response.json()\n  );\n}\n\nfunction fetchUserPosts(userId) {\n  return fetch(`https://api.rabi.com/posts?userId=${userId}`).then((response) =\u003e\n    response.json()\n  );\n}\n\nPromise.all([fetchUserData(userId), fetchUserPosts(userId)]);\n```\n\n## Read More Sources\n\n- [Promises vs Callbacks](https://stackoverflow.com/questions/22539815/arent-promises-just-callbacks#:~:text=Promises%20are%20not%20callbacks.,do%2C%20you%20get%20little%20benefit.)\n- [Callbacks in JavaScript](https://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o)\n- [Async Loops](https://www.theanshuman.dev/articles/asynchronous-loops-in-javascript-using-foreach-vs-map-vs-for-loop-5020)\n- [For loop vs ForEach](https://medium.com/@moucodes/exploring-the-difference-between-using-async-await-in-a-for-loop-and-foreach-739c9ebeb64a)\n- [ForEach issues](https://gist.github.com/joeytwiddle/37d2085425c049629b80956d3c618971)\n- [Promise Chaining](https://javascript.info/promise-chaining)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frabi-siddique%2Fjs-interview-questions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frabi-siddique%2Fjs-interview-questions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frabi-siddique%2Fjs-interview-questions/lists"}