I am reading Douglas Crockford\'s book \"Javascript: The Good Parts\". He is talking about scope and saying that JS doesn\'t have block scope:
In many mod
From my point of view, as javascript do not have block scope, declaring all variables on top of the function makes you spot easier variables you do not have to use as you can reuse an other.
Example :
function test(){
var pages = [
'www.stackoverflow.com',
'www.google.com'
];
var users = [
'John',
'Bob'
];
for (var page = 0; page < pages.length; page++) {
console.log(pages[page]);
};
for (var user = 0; user < users.length; user++) {
console.log(users[user]);
};
}
Can be changed to :
function test(){
var index, pages, users;
pages = [
'www.stackoverflow.com',
'www.google.com'
];
users = [
'John',
'Bob'
];
for (index = 0; index < pages.length; index++) {
console.log(pages[index]);
};
for (index = 0; index < users.length; index++) {
console.log(users[index]);
};
}
And save one variable space from the memory.
In such a small function the main point may not be visible, but imagine a whole project with thousand lines of code. This may make your code run faster.