1 Replies - 317 Views - Last Post: 28 January 2016 - 03:15 PM

#1 jsJim   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 28-January 16

What's With All the Anonymous / Inline Functions in JS Literature?

Posted 28 January 2016 - 02:22 PM

Hi! I'll start off by saying that I really do like javascript, and I plan to keep using it. I've been reading a lot, and it seems like most Javascript tutorials, documentation, and books love to use the inline anonymous function style which to me is so confusing and cyptic!

I came from a background in Java and actionscript 3. There were plenty of callback functions in these languages, but we just used named functions, like this:
var myVar;

function myFunction() {
    myVar = setTimeout(alertFunc, 3000);

function alertFunc() {

In javascript, I keep coming across incredibly ugly and unreadable code (in examples meant to teach people javascript!), like this:
var myVar;

function myFunction() {
    myVar = setTimeout(function(){
        alertFunc("First param", "Second param"); 
         }, 2000);

I don't see how the second way of writing the timeout function could possibly be cleaner or clearer than the first, because that is what I'M going for when making a 'style guide' for how my team and I should write functions. 

To me even one anonymous function looks bad, but thinking you are being tricky and cute by making something like this is just terrible bad for the maintainability of the code:

var p_client = new Db('integration_tests_20', new Server("", 27017, {}), {'pk':CustomPKFactory});
p_client.open(function(err, p_client) {
    p_client.dropDatabase(function(err, done) {
        p_client.createCollection('test_custom_key', function(err, collection) {
            collection.insert({'a':1}, function(err, docs) {
                collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}, function(err, cursor) {
                    cursor.toArray(function(err, items) {
                        test.assertEquals(1, items.length);
                        // Let's close the db​

Although I'm trying to be open-minded, I don't see anything good about writing functions this way other than it saves a few keystrokes and lines (which to me is not at all important compared to code clarity). Are there any fancy scoping rules or something that might make me reconsider writing functions this way? Are there any times where you want to write functions like this?

Is This A Good Question/Topic? 0
  • +

Replies To: What's With All the Anonymous / Inline Functions in JS Literature?

#2 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6834
  • View blog
  • Posts: 28,360
  • Joined: 12-December 12

Re: What's With All the Anonymous / Inline Functions in JS Literature?

Posted 28 January 2016 - 03:15 PM

Duplicate topic closed.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1