Search code examples
javascriptself-invoking-function

Self-invoking function javascript


I've tried to write this code for self-invoking function in Javascript:

var ello = ("ello");
obj = (function myFunc(){var elem= []["H" + ello]["world"]["!" + "!"]();
 return elem;
}, "as");

test = myFunc();

But at the last line I received this error message:

  • myFunc is not defined

Solution

  • You haven't written a self-invoking function.

    You've written a named function expression.

    Named function expressions generate a variable with the same name as them only inside their own scope (as opposed to function declarations which generate a variable with the same name in the scope in which the function was declared).

    In order to call a function expression you have to either immediately invoke it (by following it with ()) or assign it to a variable or property to call later. You are doing neither (while you do have an assignment operator just before it, the comma operator afterwards means that the string "as" gets assigned instead).

    (Note that the function you have written will throw errors when you call it. It makes no sense at all.)