mickey06
mickey06

Reputation: 171

Using an object to replace the switch statement

I found the following exemple on the jqfundamentals site. It seems to me that the else statement is unnecessary/wrong. So what am I missing ?

var stuffToDo = {
    'bar' : function() {
        alert('the value was bar -- yay!');
    },

    'baz' : function() {
        alert('boo baz :(');
    },

    'default' : function() {
        alert('everything else is just ok');
    }
};

if (stuffToDo[foo]) {
    stuffToDo[foo]();
} else {
    stuffToDo['default']();
}

Upvotes: 0

Views: 152

Answers (2)

jondavidjohn
jondavidjohn

Reputation: 62402

It's just checking that stuffToDo[foo] exists...

and If it doesn't call the 'default'

Not sure that I think replacing the switch statement is necessary or good, let alone a fundamental of javascript...

Upvotes: 1

Alexander Pavlov
Alexander Pavlov

Reputation: 32296

If foo is "moo", then stuffToDo['default']() will be invoked (to avoid throwing an exception.)

Upvotes: 1

Related Questions