user310291
user310291

Reputation: 38180

Why is this javascript object with simplest constructor undefined?

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 ?

Upvotes: 3

Views: 147

Answers (2)

Michael Warner
Michael Warner

Reputation: 4217

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.

Upvotes: 2

Louis Ricci
Louis Ricci

Reputation: 21086

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.

Upvotes: 2

Related Questions