3

I tested this in console :

var toto = (function() {function toto() {}})();
toto

Result in chrome console is

undefined

Why ? I would have expected as usual the constructor :

function toto() {}

What syntax error did I make ?

5
  • 2
    Your IEFE call doesn't return anything. Commented Feb 8, 2016 at 19:43
  • No syntax error, if there was one, it would be in the console. Commented Feb 8, 2016 at 19:44
  • Why are you doing this? Commented Feb 8, 2016 at 19:44
  • @Bergi I'm learning javascript OOP Commented Feb 8, 2016 at 19:46
  • @Bergi OK thanks I didn't put any return :) You can put your answer I will mark it. Commented Feb 8, 2016 at 19:48

2 Answers 2

2

If you run this code I believe this will give you the answer.

var noname = (function() {
    function toto() {
         console.log('running toto');
         return 'returning toto';
    }
    console.log(toto());
    return 'no name';
})();
console.log(noname);

The longer answer is the following.

(function(){})();

This is called an IIFE (Immediately Invoked Function Expression) it creates and calls the function right after it is created. What you place in it, is contained to that function. This is the best way to create private variables in ES5 Javascript. Like all functions you can return things from an IIFE and access variables declared outside the IIFE but nothing within from the outside, again it creates a private scope. As you have your IIFE return nothing it returns the default value undefined.

Sign up to request clarification or add additional context in comments.

Comments

2

You forgot a return.

var toto = (function() {return function toto() {}})();

The return'ed value is what's assigned to the variable, if you hve no return statement then the value returned is undefined.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.