javascriptfunctionglobalwindow-object

Function containing invalid characters in its name


I was trying to abuse function names in Chrome dev tools:

window["hello world"] = function () { console.log("Hello World!"); }

The line above will create hello world global function.

It appears in autocomplete suggestions also:

If we call it this way (hello world()) we get a syntax error, that is supposed to be so:

SyntaxError: Unexpected identifier

However, how can we call this function without using quotes (window["hello world"]())?


Solution

  • You haven't given the function a name at all. It is an anonymous function that is assigned to a property of the window object.

    Since the property name has spaces in it, you can't access it using an identifier, so the only way to get to it is to explicitly use the window object.

    window["hello world"]();
    

    If you really want to run the function without using quotes, then you can do the following. Note that this is a perverse hack and not something that you should do in production code.

    window["hello world"] = function () { console.log("Hello World!"); }
    // No quotes for any of the code used to access the above.
    window[
        [ 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100 ].map(
            function (currentValue) {
                return String.fromCharCode(currentValue);
            }
        ).join(new String)
    ]();