'How can undefined be a function?

Can you explain how does work this code block?

(function() { function undefined(){}; undefined() })()


Solution 1:[1]

undefined is not a keyword, it is just an identifier.

In the global scope, undefined is read only.

In the scope of the IIFE you have, you can create a new undefined variable that masks the global one.


Don't do that. It confuses people trying to maintain the code.

Solution 2:[2]

(function() {
  function undefined() {
    alert('d')
  };
  undefined()

  alert(undefined)
})()

alert(undefined)

This works because you are naming the function undefined inside a function. This means, inside the function's local scope, undefined = the function. As you can see if you run the code snippet, outside the function's scope, undefined = undefined once again.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quentin
Solution 2 TalinTheDev