Search code examples
javascript

What does this _=_=>_(_);_(_) mean?


I just came across this code

_=_=>_(_);_(_)

and it's written in javascript. I have no idea what this does. What does this smiley code mean?


Solution

  • Breaking down the syntax:

    • _=… implicitly declares a global variable named _ and assigns to it the result of the expression to the right. This would throw an error in strict mode, unless the variable was already declared elsewhere.
    • _=>… is a arrow function, also called lambda expression, that accepts a parameter named _ (which will shadow the name of the global variable) and returns the result of the expression to the right.
    • _(_) calls the parameter _ as though its a function, passing in _ as the first argument to that function. This works because JavaScript features first-class functions, so they can be used as arguments to other functions or be returned from functions (this is not true in all languages).

    So far, _=_=>_(_); creates a higher-order function that accepts a function as a parameter and calls that second function with itself as an argument, then assigns it to a global variable named _.

    • the final _(_) will call the global variable _ with the same global variable, _ as an argument.

    The result would be a pretty quick stack overflow, since this is effectively a recursive function without any escape condition. However, modern browsers will most likely gracefully break out of the infinite recursion by throwing an error rather than simply crashing.

    try {
        _=_=>_(_);_(_)
    } catch (error) {
        console.log(error.toString());
    }