10. How does an IIFE work in JavaScript, and why would you use it? Also provide an example
hard

An Immediately Invoked Function Expression (IIFE) is a function that is immediately executed as soon as it is defined. This is done by wrapping the function expression in parentheses and invoking it with the () operator, immediately after it has been defined.

The reason for using IIFE is to ensure that the function is only executed once, when it is first created. It also allows us to define variables that are scoped only within the IIFE, and not accessible outside of it. This can be useful for creating private variables or functions that should not be accessed from other parts of the code.

Here's an example:

(function() {
  var secret = "This is a secret variable";

  function privateFunction() {
    console.log("This is a private function");
  }
})();

// Accessing the secret variable and private function from outside of the IIFE will result in an error
console.log(secret); // Uncaught ReferenceError: secret is not defined
privateFunction(); // Uncaught TypeError: Cannot read property 'privateFunction' of undefined

In this example, we define an IIFE that creates a private variable secret and a private function privateFunction. The function is immediately executed as soon as it is defined, and the variables are scoped only within the IIFE. If we try to access these variables or functions from outside of the IIFE, we will get an error because they are not defined in that scope.