{"id":22814310,"url":"https://github.com/devinterview-io/javascript-interview-questions","last_synced_at":"2026-03-07T02:32:52.569Z","repository":{"id":38403516,"uuid":"331563940","full_name":"Devinterview-io/javascript-interview-questions","owner":"Devinterview-io","description":"🟣 Javascript interview questions and answers to help you prepare for your next technical interview in 2025.","archived":false,"fork":false,"pushed_at":"2025-05-19T16:57:37.000Z","size":39,"stargazers_count":154,"open_issues_count":0,"forks_count":19,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-19T18:00:36.496Z","etag":null,"topics":["coding-interview-questions","coding-interviews","interview-practice","interview-prep","interview-preparation","javascript","javascript-interview-questions","javascript-questions","javascript-tech-interview","leetcode-questions","leetcode-solutions","programming-interview-questions","software-developer-interview","software-engineer-interview","software-engineering","technical-interview-questions","web-and-mobile-development-interview-questions"],"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/Devinterview-io.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,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2021-01-21T08:32:20.000Z","updated_at":"2025-05-19T16:57:41.000Z","dependencies_parsed_at":"2025-04-22T18:51:37.193Z","dependency_job_id":null,"html_url":"https://github.com/Devinterview-io/javascript-interview-questions","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Devinterview-io/javascript-interview-questions","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fjavascript-interview-questions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fjavascript-interview-questions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fjavascript-interview-questions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fjavascript-interview-questions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Devinterview-io","download_url":"https://codeload.github.com/Devinterview-io/javascript-interview-questions/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fjavascript-interview-questions/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30206070,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-06T19:07:06.838Z","status":"online","status_checked_at":"2026-03-07T02:00:06.765Z","response_time":53,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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-interview-questions","coding-interviews","interview-practice","interview-prep","interview-preparation","javascript","javascript-interview-questions","javascript-questions","javascript-tech-interview","leetcode-questions","leetcode-solutions","programming-interview-questions","software-developer-interview","software-engineer-interview","software-engineering","technical-interview-questions","web-and-mobile-development-interview-questions"],"created_at":"2024-12-12T13:08:03.871Z","updated_at":"2026-03-07T02:32:52.530Z","avatar_url":"https://github.com/Devinterview-io.png","language":null,"readme":"# 100 Common JavaScript Interview Questions\n\n\u003cdiv\u003e\n\u003cp align=\"center\"\u003e\n\u003ca href=\"https://devinterview.io/questions/web-and-mobile-development/\"\u003e\n\u003cimg src=\"https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/github-blog-img%2Fweb-and-mobile-development-github-img.jpg?alt=media\u0026token=1b5eeecc-c9fb-49f5-9e03-50cf2e309555\" alt=\"web-and-mobile-development\" width=\"100%\"\u003e\n\u003c/a\u003e\n\u003c/p\u003e\n\n#### You can also find all 100 answers here 👉 [Devinterview.io - JavaScript](https://devinterview.io/questions/web-and-mobile-development/javascript-interview-questions)\n\n\u003cbr\u003e\n\n## 1. What are the _data types_ present in JavaScript?\n\nJavaScript has **primitive** and **composite** data types.\n\n### Primitive Data Types\n\n- **Boolean**: Represents logical values of **true** or **false**.\n- **Null**: Denotes the lack of a value.\n\n- **Undefined**: Indicates a variable that has been declared but has not been assigned a value.\n\n- **Number**: Represents numeric values, including integers and floats.\n\n- **BigInt**: Allows for representation of integers with arbitrary precision.\n\n- **String**: Encapsulates sequences of characters.\n\n- **Symbol** (ES6): Provides a unique, immutable value.\n\n### Composite Data Types\n\n- **Object**: Represents a set of key-value pairs and is used for more complex data structures.\n- **Function**: A callable object that can be defined using regular function syntax or using the `new Function()` constructor (rarely used).\n\n### Notable Characteristics\n\n- JavaScript is **dynamically-typed**, meaning the data type of a variable can change during the execution of a program.\n- **Data type coercion** can occur, where values are implicitly converted from one type to another in specific contexts, such as during comparisons.\n- Arithmetic operations, particularly when one of the operands is a string, can lead to **implicit type conversions**.\n\u003cbr\u003e\n\n## 2. What is the difference between _null_ and _undefined_?\n\nWhile both **null** and **undefined** represent \"no value\" in JavaScript, they are distinct in their roles and origins.\n\n### Origin and Context\n\n- **null** usually denotes an intentionally **absent** value, and developers can set a variable to null to signify the absence of an object or a value. For example, if an API call doesn't return data, you might set a variable to null.\n\n- **undefined** typically indicates a variable that has been declared but not yet been assigned a value, or a property that doesn't exist on an object.\n\n### Variable Initialization and Assignment\n\n- Variables that haven't been assigned a value are `undefined` by default, unless explicitly set to `null`.\n  ```javascript\n  let foo; // undefined\n  let bar = null; // null\n  ```\n\n### Function Arguments\n\n- When a function is called, and the parameter isn't provided or its value is not set, the parameter is `undefined`. \n- **null** would instead be an explicit value provided as an argument.\n\n### Object Properties\n\n- If you try to access a property on an object that doesn't exist, the result is `undefined`.\n  ```javascript\n  let obj = {};\n  console.log(obj.nonExistentProperty); // undefined\n  ```\n\n- **Null** can be used to clear a property value in an object that was previously set.\n  ```javascript\n  let obj = { prop: 'value' };\n  obj.prop = null;\n  ```\n\n### The Equality Operation\n\n- In JavaScript, **undefined** and **null** are treated as equal when using loose equality (==) but not strict equality (===).\n\n### Use-Cases and Best Practices\n\n- When you initialize a variable and are not ready to assign a meaningful value, it's more common to use **undefined** instead of **null** to indicate that the value isn't there yet.\n- For example, if you declare a user object but don't have their details yet, you might keep it as `undefined`.\n\n### Code Example\n\nHere is the JavaScript code:\n\n```javascript\nlet var1;\nlet var2 = null;\n\nlet object = {\n  a: 1,\n  b: undefined\n};\n\nfunction test(arg1, arg2) {\n  console.log(arg1);  // undefined: not provided\n  console.log(arg2);  // null: provided as such\n}\n\nfunction clearProperty(prop) {\n  delete object[prop];\n}\n\nconsole.log(var1);     // undefined\nconsole.log(var2);     // null\nconsole.log(object.a); // 1\nconsole.log(object.b); // undefined\nconsole.log(object.c); // undefined\n\ntest();               // Both arguments are undefined\ntest(1, null);        // arg1 is 1, arg2 is null\n\nclearProperty('b');  // Removes property 'b' from object\nconsole.log(object.b); // undefined: Property 'b' was removed, not set to null\n```\n\u003cbr\u003e\n\n## 3. How does JavaScript handle _type coercion_?\n\n**Type Coercion** in JavaScript refers to the automatic conversion of values from one data type to another.\n\n### Explicit and Implicit Coercion\n\n- **Explicit**: Achieved through methods such as `parseInt()`, `Number()`, and `toString()`.\n- **Implicit**: Automatically occurs during operations or comparisons. For example, combining a string and a number in an addition results in the automatic conversion of the number to a string.\n\n### Common Coercion Scenarios\n\n1. **Arithmetic Operations**: Strings are coerced to numbers.\n    - **Example**: `\"5\" - 3` evaluates to `2`, as the string is coerced to a number.\n    \n2. **Loose Equality (==)**: Data types are often modified for comparisons.\n    - **Example**: `\"4\" == 4` is `true` due to string coercion before the comparison.\n\n3. **Conditionals** (if and Ternary Operators): Truthiness or falsiness is determined.\n    - **Example**: `if(1)` evaluates to `true` because `1` coerces to `true`.\n\n4. **Logical Operators**: Non-boolean values are coerced to booleans.\n    - **Example**: `\"hello\" \u0026\u0026 0` evaluates to `0` because the truthy `\"hello\"` short-circuits the `\u0026\u0026` operation, and `0` coerces to `false`.\n\u003cbr\u003e\n\n## 4. Explain the concept of _hoisting_ in JavaScript.\n\n**Hoisting** is a JavaScript mechanism that involves moving variable and function declarations to the top of their containing scope **during the compile phase**. However, the assignments to these variables or the definitions of functions remain in place.\n\nFor instance, even though the call to `myFunction` appears before its definition, hoisting ensures that it doesn't cause an error.\n\n### Hoisting in Action\n\nHere's a Code Example:\n\n```javascript\nconsole.log(myVar); // Undefined\nvar myVar = 5;\n\nconsole.log(myVar); // 5\n\n// The above code is equivalent to the following during the compile phase:\n// var myVar;\n// console.log(myVar);\n// myVar = 5;\n\nconsole.log(sayHello()); // \"Hello, World!\"\nfunction sayHello() {\n    return \"Hello, World!\";\n}\n\n// The above code is equivalent to the following during the compile phase:\n// function sayHello() {\n//     return \"Hello, World!\";\n// }\n// console.log(sayHello());\n```\n\n### Why Hoisting Matters\n\nUnderstanding hoisting can help you prevent certain unexpected behaviors in your code. For example, it can shed light on unexpected \"undefined\" values that might appear even after a variable is declared and initialized.\n\n#### Global Scope and Hoisting\n\nIn the global scope, variables declared with `var` and functions are always hoisted to the top. For example:\n\n```javascript\n// During the compile phase, the following global declarations are hoisted:\n// var globalVar;\n// function globalFunction() {}\n\nconsole.log(globalVar); // Undefined\nconsole.log(globalFunction()); // \"Hello, Global!\"\nvar globalVar = \"I am global Var!\";\nfunction globalFunction() {\n    return \"Hello, Global!\";\n}\n```\n\n#### Local Scope and Hoisting\n\nVariables and functions declared in local scopes within functions are also hoisted to the top of their scope.\n\nHere's a Code Example:\n\n```javascript\nfunction hoistingInLocalScope() {\n    // These local declarations are hoisted during the compile phase:\n    // var localVar;\n    // function localFunction() {}\n\n    console.log(localVar); // Undefined\n    localVar = \"I am a local var!\";\n    console.log(localFunction()); // \"Hello, Local!\"\n\n    var localVar;\n    function localFunction() {\n        return \"Hello, Local!\";\n    }\n}\n```\n\n### Best Practices\n\nTo write clean, readable code, it's important to:\n\n- Declare variables at the top of your scripts or functions to avoid hoisting-related pitfalls.\n- Initialize variables before use, **regardless of hoisting**, to ensure predictable behavior.\n\n### ES6 and Hoisting\n\nWith the introduction of `let` and `const` in ES6, JavaScript's behavior has adapted. Variables declared using `let` and `const` are still hoisted, but unlike `var`, they are **not initialized**.\n\nHere's an Example:\n\n```javascript\nconsole.log(myLetVar); // ReferenceError: Cannot access 'myLetVar' before initialization\nlet myLetVar = 5;\n```\n\n### Constants and Hoisting\n\n`const` and `let` behave similarly when hoisted, but their difference lies in the fact that `const` must be assigned a value at the time of declaration, whereas `let` does not require an initial value.\n\nHere's an Example:\n\n```javascript\nconsole.log(myConstVar); // ReferenceError: Cannot access 'myConstVar' before initialization\nconst myConstVar = 10;\n\nconsole.log(myLetVar); // Undefined\nlet myLetVar = 5;\n```\n\u003cbr\u003e\n\n## 5. What is the _scope_ in JavaScript?\n\n**Scope** defines the accessibility and lifetime of variables in a program. In JavaScript, there are two primary types: **Global Scope** and **Local Scope**.\n\n### Global Scope\n\nAny variable declared **outside of a function** is in the global scope. These can be accessed from both within functions and from other script tags.\n\n#### Example: Global Scope\n\nHere is the JavaScript code:\n\n```javascript\nlet globalVar = 'I am global';\n\nfunction testScope() {\n    console.log(globalVar); // Output: 'I am global'\n}\n\ntestScope();\nconsole.log(globalVar); // Output: 'I am global'\n```\n\n### Local Scope\n\nVariables declared within a **function** (using `let` or `const` or prior to JavaScript ES6 with `var`) have local scope, meaning they are only accessible within that function.\n\n#### Example: Local Scope\n\nHere is the JavaScript code:\n\n```javascript\nfunction testScope() {\n    let localVar = 'I am local';\n    console.log(localVar); // Output: 'I am local'\n}\n\n// This statement will throw an error because localVar is not defined outside the function scope\n// console.log(localVar);\n```\n\n### Block Scope\n\nStarting from **ES6**, JavaScript also supports block scope, where variables defined inside code blocks (denoted by `{}` such as loops or conditional statements) using `let` or `const` are accessible only within that block.\n\n#### Example: Block Scope\n\nHere is the JavaScript code:\n\n```javascript\nfunction testScope() {\n    let localVar = 'I am local';\n    if (true) {\n        let blockVar = 'I am local to this block';\n        console.log(localVar, blockVar); // Both will be accessible\n    }\n    // This statement will throw an error because blockVar is not defined outside the block scope\n    // console.log(blockVar);\n}\n\ntestScope();\n```\n\u003cbr\u003e\n\n## 6. What is the difference between `==` and `===`?\n\n**Strict equality** (`===`) in JavaScript requires both value and type to match, testing for more specific conditions and reducing the likelihood of unexpected results.\n\nIn contrast, the **abstract equality** comparison (`==`) can lead to type coercion, potentially causing counterintuitive outcomes.\n\nWhile both comparison modes test value equality, `===` ensures an additional match of data type.\n\n### Illustrative Example: Abstract vs. Strict Equality\n\n- Abstract Equality: \n    - `5 == '5'` evaluates to `true` because JavaScript converts the string to a number for comparison.\n- Strict Equality:\n    - `5 === '5'` evaluates to `false` because the types are not the same.\n\n### Key Considerations\n\n- **Type Safety**: `===` is safer as it avoids unwanted type conversions.\n- **Performance**: `===` can be faster, especially for simple comparisons, as it doesn't involve type coercion or additional checks.\n- **Clarity**: Favoring `===` can make your code clearer and more predictable.\n\n### Common Best Practices\n\n- **Use Strict Equality by Default**: This approach minimizes unintended side effects.\n- **Consider Type Coercion Carefully**: In specific cases or with proven understanding, `==` can be suitable, but be cautious about potential confusion.\n\n### Code Example: Equality Operators\n\nHere is the JavaScript code:\n\n```javascript\n// Abstract equality\nconsole.log('5' == 5);      // true\nconsole.log(null == undefined);  // true\nconsole.log(0 == false);    // true\n\n// Strict equality\nconsole.log('5' === 5);     // false\nconsole.log(null === undefined); // false\nconsole.log(0 === false);   // false\n```\n\u003cbr\u003e\n\n## 7. Describe _closure_ in JavaScript. Can you give an example?\n\nIn JavaScript, **closures** enable a **function** to access its outer scope, retaining this access even after the parent function has finished executing. This mechanism provides a powerful tool for data encapsulation and privacy.\n\n### Core Concept\n\nWhen a **function** is defined within another function, it maintains a reference to the variables from the outer function, even after the outer function has completed execution and its local variables are typically no longer accessible.\n\n### Key Components\n\n1. **Outer Function (Parent function)**: It contains the inner functions or closures.\n2. **Inner Function (Closure)**: Defined within the parent function, it references variables from the outer function.\n3. **Lexical Environment**: The context where the inner function is defined, encapsulating the scope it has access to.\n\n### Example: Password Generator\n\nConsider a simple scenario of a function in charge of generating a secret password:\n\n1. The outer function, `generatePassword`, defines a local variable, `password` and returns an inner function `getPassword`.\n2. The inner function, `getPassword`, has exclusive access to the `password` variable even after `generatePassword` has executed.\n\nHere is the JavaScript code:\n\n```javascript\nfunction generatePassword() {\n  let password = '';\n  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n  const passwordLength = 8;\n  for(let i = 0; i \u003c passwordLength; i++) {\n    password += characters.charAt(Math.floor(Math.random() * characters.length));\n  }\n\n  return function getPassword() {\n      return password;\n  };\n}\n\nconst getPassword = generatePassword();\n\nconsole.log(getPassword()); // Outputs the generated password.\n```\n\nIn this example, `getPassword` still has access to the `password` variable after the `generatePassword` function has completed, thanks to the closure mechanism.\n\n### Application\n\n- **Data Privacy**: JavaScript design patterns like the Module and Revealing Module Patterns use closures to keep data private.\n\n- **Timeouts and Event Handlers**: Closures help preserve the surrounding context in asynchronous operations such as `setTimeout` and event handlers.\n\n### Pitfalls to Avoid\n\n- **Memory Leakage**: If not used carefully, closures can cause memory leaks, as the outer function's variables continue to live in memory because of the closure link.\n- **Stale Data**: Be mindful of shared variables that might change after a closure has been defined, leading to unexpected behavior.\n\n### Browser Compatibility\n\nThe concept of closures is a fundamental aspect of the JavaScript language and is supported by all modern browsers and environments.\n\u003cbr\u003e\n\n## 8. What is the '_this_ keyword' and how does its context change?\n\nIn JavaScript, the context of **`this`** refers to the execution context, typically an object that owns the function where `this` is used.\n\n### 'this' in the Global Scope\n\nIn **non-strict** mode, `this` in the global scope refers to the `window` object. In **strict** mode, `this` is `undefined`.\n\n### 'this' in Functions\n\nIn **non-arrow functions**, the value of `this` depends on how the function is **invoked**. When invoked:\n\n- As a method of an object: `this` is the object.\n- Alone: In a browser, `this` is `window` or `global` in Node.js. In strict mode, it's `undefined`.\n- With `call`, `apply`, or `bind`: `this` is explicitly set.\n- As a constructor (with `new`): `this` is the newly created object.\n\n### 'this' in Arrow Functions\n\nArrow functions have a **fixed context** for `this` defined at **function creation** and are not changed by how they are invoked.\n\n- They do **not have** their own `this`.\n- They use the `this` from their surrounding lexical context (the enclosing function or global context).\n\n### Code Example: Global Context\n\nHere is the JavaScript code:\n\n```javascript\n// Main\nlet globalVar = 10;\n\nfunction globalFunction() {\n    console.log('Global this: ', this.globalVar);\n    console.log('Global this in strict mode: ', this);\n}\n\nglobalFunction();  // Output: 10, window or undefined (in strict mode)\n\n// In Node.js, it will be different, because \"window\" is not defined. But \"this\" will refer to the global object.\n```\n\u003cbr\u003e\n\n## 9. What are _arrow functions_ and how do they differ from regular functions?\n\nLet's look at the key features of **arrow functions** and how they differ from traditional functions in JavaScript.\n\n### Arrow Functions: Key Features\n\n- **Concise Syntax**:\n  - Especially useful for short, one-liner functions.\n  - No need for `function` keyword or **braces** if there's a single expression.  \n  \n- **Implicit Return**:\n  - When there's no explicit `{ return ... ;}` statement, arrow functions return the result of the single expression inside.\n\n- **`this` Binding**:\n  - Does not have its **own `this`**. It's \"inherited\" from the surrounding (lexical) context. This feature is known as '**lexical scoping**'.\n\n### Code Example: Standard Function vs. Arrow Function\n\nHere is the JavaScript code:\n\n```javascript\n// Standard Function\nfunction greet(name) {\n  return \"Hello, \" + name + \"!\";\n}\n\n// Arrow Function\nconst greetArrow = name =\u003e \"Hello, \" + name + \"!\";\n```\n\nIn the code above, `greet` is a standard function, while `greetArrow` is an arrow function, showcasing the difference in syntax and required keywords.\n\n### When to Use Arrow Functions\n\n- **Event Handlers**: Ideal for concise, inline event handling, where `this` context can be inherited from the lexical scope.\n\n- **Callback Functions**: Useful for array methods like `map`, `filter`, and `reduce`.\n\n- **Avoidance of `this` Redefinition**: When you want to maintain the surrounding context of `this` and avoid unintended redefinition.\n\n### Code Example: Arrow Function and `this` Context\n\nHere is the JavaScript code:\n\n```javascript\n// Using traditional functions\ndocument.getElementById('myButton').onclick = function() {\n  console.log('Button clicked:', this);  // Refers to the button element\n};\n\n// Using arrow functions\ndocument.getElementById('myButton').onclick = () =\u003e {\n  console.log('Button clicked:', this);  // Refers to the global/window object\n};\n```\n\nIn the arrow function example, the context of `this` does not refer to the button element, but to the global `window` object, because arrow functions do not have their own binding of `this`. Instead, they inherit `this` from their lexical scope, which in this case is the global context.\n\u003cbr\u003e\n\n## 10. What are _template literals_ in JavaScript?\n\n**Template literals** are a feature in modern JavaScript versions that offer a more flexible and readable way to work with strings. They are often referred to as \"template strings\".\n\n### Key Features\n\n- **Multiline Text**: Template literals support multiline strings without requiring escape characters or string concatenation with a `+` sign.\n- **String Interpolation**: They enable the seamless embedding of JavaScript expressions within strings, using `${}`.\n\n### Syntax\n\n- **Single Versus Double Quotes**: For template literals, use backticks (\\`) instead of single quotes ('') or double quotes (\"\").\n- **Placeholder**: The `${expression}` placeholder within the backticks allows for variable and expression injection.\n\n### Example:\n\n```javascript\nlet name = \"John\";\nlet message = `Hi ${name}!`;\n\nconsole.log(message);  // Output: \"Hi John!\"\n```\n\n### Benefits\n\n- **Readability**: They can make code more understandable, especially when dealing with longer or complex strings, by keeping content closer to its intention.\n- **Interpolation \u0026 Expression**: Template literals reduce verbosity and rendering logic when integrating dynamic data.\n\n### Code Example: Multiline Text and String Interpolation\n\n```javascript\n// Regular String\nlet poem = \"Roses are red,\\nViolets are blue,\\nSugar is sweet,\\nAnd so are you.\";\n\n// Template Literal\nlet poemTemplate = `\n  Roses are red,\n  Violets are blue,\n  Sugar is sweet,\n  And so are you.\n`;\n```\n\n### Browser Compatibility Concerns\n\nTemplate literals are universally supported in modern browsers and are now considered a **core JavaScript feature**. However, they may not work in older browsers such as Internet Explorer without transpilation or polyfilling.\n\u003cbr\u003e\n\n## 11. What is a _higher-order function_ in JavaScript?\n\nA **higher-order function** in JavaScript is a function that can take other functions as arguments or can return functions. This feature enables functional programming paradigms such as `map`, `reduce`, and `filter`. Higher-order functions offer versatility and modularity, fostering streamlined, efficient code.\n\n### Key Characteristics\n\n- **First-class functions**: Functions in JavaScript are considered first-class, meaning they are a legitimate data type and can be treated like any other value, including being assigned to variables, stored in data structures, or returned from other functions.\n\n- **Closure support**: Due to closures, a higher-order function can transport not just the enclosed data within the function definition, but also the lexical environment in which that data resides.\n\n- **Dynamic code**: Because JavaScript allows functions to be dynamically constructed and named, they can be dynamically passed to higher-order functions.\n\n### Practical Applications\n\n- **Callback Execution**: Functions like `setTimeout` and `addEventListener` take a function as an argument and are thus higher-order.\n\n- **Event Handling**: Many event-driven systems leverage higher-order functions for tasks such as event subscription and emission.\n\n- **Iterative Operations**: The `map`, `filter`, and `reduce` functions in JavaScript operate on arrays and require functions to be passed, making them higher-order.\n\n- **Code Abstraction**: Higher-order functions enable the encapsulation of repetitive tasks, promoting cleaner, more readable code.\n\n### Code Example: Higher-order Functions\n\nHere is the JavaScript code:\n\n```javascript\n// Simple higher-order function\nfunction multiplier(factor) {\n  return function(num) {\n    return num * factor;\n  };\n}\n\n// Invoke a higher-order function\nconst twice = multiplier(2);\nconsole.log(twice(5));  // Output: 10\n\n// Functional programming with higher-order functions\nconst numbers = [1, 2, 3, 4, 5];\nconst doubled = numbers.map(multiplier(2));  // [2, 4, 6, 8, 10]\nconst tripled = numbers.map(multiplier(3));  // [3, 6, 9, 12, 15]\n```\n\u003cbr\u003e\n\n## 12. Can functions be assigned as values to variables in JavaScript?\n\nYes, **JavaScript** supports first-class functions, meaning **functions can be treated as variables** and then assigned to other variables or passed as arguments to other functions.\n\nFunctions defined as regular functions or arrow functions are both first-class in JavaScript. \n\n### Practical Code Example\n\nHere is the JavaScript code:\n\n```javascript\n// Define a function\nfunction greet() {\n  console.log('Hello!');\n}\n\n// Assign the function to a variable\nlet sayHello = greet;\n\n// Call the function through the variable\nsayHello();  // Output: \"Hello!\"\n\n// Reassign the variable to a new function\nsayHello = function() {\n  console.log('Bonjour!');\n};\n\n// Call it again to see the new behavior\nsayHello();  // Output: \"Bonjour!\"\n```\n\n### Practical Use Cases\n\n- **Callbacks**: Functions can be passed as parameters to other functions.\n  \n- **Event Handling**: In web development, functions define how to respond to specific events, and these functions are often attached to event listeners.\n\n- **Modular Development**: In programming patterns like the Module pattern, functions are defined within a scope and then returned, similar to variables.\n\n- **Higher-Order Functions**: These functions operate on other functions, taking them as arguments or returning them, and are an essential part of many modern JavaScript libraries and frameworks.\n\u003cbr\u003e\n\n## 13. How do _functional programming_ concepts apply in JavaScript?\n\n**Functional Programming** (FP) concepts in JavaScript are a direct result of the language's first-class functions. Key FP principles, such as immutability, pure functions, and **declarative** style, play a crucial role.\n\n### Core Concepts\n\n#### First-Class Functions and Higher-Order Functions\n\nJavaScript treats functions as first-class citizens, allowing them to be assigned to variables, passed as parameters, and returned from other functions. This feature is foundational to FP in the language.\n\n#### Code Example:\n\nHere is the JavaScript code:\n\n```javascript\nconst sayHello = () =\u003e console.log('Hello!');\nconst runFunction = (func) =\u003e func();\n\nrunFunction(sayHello);  // Output: \"Hello!\"\n```\n\u003cbr\u003e\n\n## 14. What are _IIFEs_ (Immediately Invoked Function Expressions)?\n\nThe **Immediately Invoked Function Expression** (IIFE) design pattern employs an anonymous function that gets executed promptly after its definition.\n\nKey characteristics of IIFEs include localized variable scopes and immediate activation upon interpreter parsing.\n\n### Code Example: IIFE\n\nHere is the JavaScript code:\n\n```javascript\n(function(){\n    var foo = 'bar';\n    console.log(foo);\n})();\n```\n\nIn this example, the function is enclosed within parentheses, ensuring the enclosed function is evaluated as an expression. Subsequently, it is invoked with a trailing pair of parentheses.\n\n### Core Functions of IIFE\n\n1. **Encapsulation**: Through lexical scoping, IIFEs safeguard variables from leaking into the global scope. This, in turn, averts unintended variable tampering in the global context.\n\n2. **Data Hiding**: Internal functions or data can be hidden from external access, providing a mechanism for information concealment and access control.\n\n3. **Initialization**: The IIFE structure is ideal for setting up initial conditions, like binding events or pre-processing data.\n\n### Use Cases\n\n- **Avoiding Variable Pollution**: When interfacing with libraries or inserting code snippets, IIFEs prevent global scope pollution.\n\n- **Module Patterns**: IIFEs, in combination with **closures**, lay the groundwork for modular code organization by shielding private variables and functions.\n\n### Modern Alternatives\n\nWith the introduction of ES6 and its `let` and `const` declarations, as well as block-scoped lexical environments, the necessity of IIFEs has reduced. Additionally, **arrow functions** provide a more concise method for defining immediately invoked functions.\n\n### IIFE Variants\n\n1. **Parentheses Invocation**: A pair of parentheses immediately invoke the enclosed function. While this approach is more extensive, it's devoid of self-documenting advantages.\n    ```javascript\n    (function(){\n        console.log('Invoked!');\n    })();\n    ```\n\n2. **Wrapping in Operators**: Similar to using parentheses for invocation, the `!`, `+`, or `-` operators are sometimes used for invoking clarity. For instance:\n    ```javascript\n    !function(){\n        console.log('Invoked!');\n    }();\n    ```\n\n3. **Named IIFE**: Though not as common, naming an IIFE can assist with self-referencing. This is most effective when the intention is to have a more comprehensive stack trace during debugging.\n    ```javascript\n    (function factorial(n){\n        if (n \u003c= 1) return 1;\n        return n * factorial(n-1);\n    })(5);\n    ```\n\n#### Caution on Minification\n\nWhen leveraging IIFEs, exercise caution while using minifiers to shrink JavaScript files. Minification might lead to unintended outcomes, altering the previous scope expectations.\n\u003cbr\u003e\n\n## 15. How do you create _private variables_ in JavaScript?\n\nIn JavaScript, encapsulating private state within an object can be achieved using a **closure**. This ensures the state is local to the object and not directly accessible from outside.\n\n### How Closures Work\n\nA **closure** allows a function to retain access to the **lexical environment** (the set of variable bindings at the point of function declaration) in which it was defined, even when the function is executed outside that lexical environment.\n\nThis means that any **inner function**, defined inside another function, has access to the **outer function's variables**, and that access is maintained even after the outer function has finished executing.\n\nFor example:\n```javascript\nfunction outerFunction() {\n    let outerVar = 'I am outer';  // This variable is in the lexical environment of outerFunction\n\n    function innerFunction() {\n        console.log(outerVar);  // Accesses outerVar from the lexical environment of outerFunction\n    }\n\n    return innerFunction;\n}\n\nlet myInnerFunction = outerFunction();\nmyInnerFunction();  // Logs: \"I am outer\"\n```\n\nHere, `innerFunction` retains access to `outerVar`.\n\n### Practical Implementation with Constructor Functions and Modules\n\n#### Constructor Functions\n\nWhen defining a JavaScript **constructor function** with `function` and `new`, closure can be used to associate private state with each instance:\n\n```javascript\nfunction Gadget() {\n    let secret = 'top secret';\n    this.setSecret = function (value) {\n        secret = value;\n    };\n    this.getSecret = function () {\n        return secret;\n    };\n}\n\nlet phone = new Gadget();\nphone.setSecret('new secret');\nconsole.log(phone.getSecret());  // 'new secret'\n```\n\nIn this example, `secret` is private to each `Gadget` instance, thanks to closure.\n\n#### Modules\n\nIn modern JavaScript, **module patterns** combined with **immediately-invoked function expressions** (IIFE) are often used for encapsulation and data hiding.\n\n- The **revealing module pattern** enables selective exposure of private members.\n\n- The **IIFE pattern** immediately executes and returns the object to be assigned, effectively creating a module.\n\nHere is the code:\n\n```javascript\nlet myModule = (function () {\n    let privateVariable = 'I am private';\n\n    function privateMethod() {\n        console.log('I am a private method');\n    }\n\n    return {\n        publicMethod: function () {\n            console.log('I am a public method');\n        },\n        getPrivateVariable: function () {\n            return privateVariable;\n        }\n    };\n})();\n\nconsole.log(myModule.getPrivateVariable());  // 'I am private'\nmyModule.privateMethod();  // Throws an error because privateMethod is not exposed\n```\n\nIn this example, `privateVariable` and `privateMethod` are accessible only within the IIFE's lexical environment, thus making them private.\n\nJavaScript tools like TypeScript and Babel also offer modules such as `module.export`, providing additional options for encapsulation.\n\u003cbr\u003e\n\n\n\n#### Explore all 100 answers here 👉 [Devinterview.io - JavaScript](https://devinterview.io/questions/web-and-mobile-development/javascript-interview-questions)\n\n\u003cbr\u003e\n\n\u003ca href=\"https://devinterview.io/questions/web-and-mobile-development/\"\u003e\n\u003cimg src=\"https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/github-blog-img%2Fweb-and-mobile-development-github-img.jpg?alt=media\u0026token=1b5eeecc-c9fb-49f5-9e03-50cf2e309555\" alt=\"web-and-mobile-development\" width=\"100%\"\u003e\n\u003c/a\u003e\n\u003c/p\u003e\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevinterview-io%2Fjavascript-interview-questions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdevinterview-io%2Fjavascript-interview-questions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevinterview-io%2Fjavascript-interview-questions/lists"}