What is the correct term for this

I was looking at the Web SQL spec on the W3C site (here)

the example code

function [U][B]prepareDatabase[/B][/U](ready, error) {
  return openDatabase('documents', '1.0', 'Offline document storage', 5*1024*1024, function (db) {
    db.changeVersion('', '1.0', function (t) {
      t.executeSql('CREATE TABLE docids (id, name)');
    }, error);
  });
}

function showDocCount(db, span) {
  db.readTransaction(function (t) {
    t.executeSql('SELECT COUNT(*) AS c FROM docids', [], function (t, r) {
      span.textContent = r.rows[0].c;
    }, function (t, e) {
      // couldn't read database
      span.textContent = '(unknown: ' + e.message + ')';
    });
  });
}

[B]p[U]repareDatabase[/U][/B](function(db) {
  // got database
  var span = document.getElementById('doc-count');
  showDocCount(db, span);
}, function (e) {
  // error getting database
  alert(e.message);
});

I don’t understand how/why prepareDatabase is set twice.

Is there a term for this? I can’t for the life of me think what it is. I know I’ve seen it before though.

I’m sure it’s very simple but if someone could just point me in the right direction I’d very much appreciate it.

It’s not set twice. The second occurrence is calling the function, not defining it. They use annonymous functions as arguments. Equivalent to this


var funcThatGetsCalledWhenReady = function(db) {
  // got database
  var span = document.getElementById('doc-count');
  showDocCount(db, span);
};
var funcThatGetsCalledWhenError = function (e) {
  // error getting database
  alert(e.message);
};

prepareDatabase(funcThatGetsCalledWhenReady, funcThatGetsCalledWhenError);

ah, ok. I think I’ve got it now. thanks.

The reason they didn’t is because no other part of the code needed a reference to either of those functions, so there’s simply no reason to create variables to reference them. It depends, but sometimes the code can be a bit easier to read if you do it anyway.

functions are pretty much the heart and soul of javascript, so it’s common to use lots and lots of functions, and many of them are just created anonymously.