Assign object to variable in node.js

Could someone explain me why I can't pass the rows Object to the clubs variable?

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'test'
});
var competition_feed = 'England';
var season_id = 2014;
var clubs = {};

connection.connect();

connection.query('SELECT * FROM clubs WHERE competition_feed=\''+competition_feed+'\' AND season_id='+season_id+';', function(err, rows, fields) {
    if (err) throw err;
    clubs = rows;
});

console.log(clubs);

connection.end();

It seems I'm missing something about variables and scope. Please help :)

You can, the reason this doesn't work is because

connection.query(.....)

Is asynchronous. So clubs isn't set to rows until later in the event loop. Much after you are trying to use it. One way to achieve the behavior you want is as follows:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'test'
});
var competition_feed = 'England';
var season_id = 2014;
var clubs = {};

connection.connect();

connection.query('SELECT * FROM clubs WHERE competition_feed=\''+competition_feed+'\' AND season_id='+season_id+';', function(err, rows, fields) {
    if (err) throw err;
    clubs = rows;
    logClubs();
});

function logClubs() {
    console.log(clubs);
}


connection.end();

clubs = rows is executed asynchronously. If you put a console.log right before clubs = rows, you will see it actually executes afterwards despite coming first in the code.