It used to be a method to make code clearer, back when we only had var, which gets hoisted. For example, the following is a pretty common error you still see nowadays:
for (var i = 0; i < arr.length; i++) {
arr[i].addEventListener('click', function() {
console.log(i);
});
}
If a coding style or a linter required the var i to be extracted out of the loop and declared at the top of the function, it becomes clearer that there's only one binding of i, and that by the end of the loop, i === arr.length, possibly prompting the coder to fix the logic error before having to run it at all:
var i = 0;
for (; i < arr.length; i++) {
arr[i].addEventListener('click', function() {
console.log(i);
});
}
But now that we have const and let, which are not hoisted out of loops (they have block scope, not function scope), the manual hoisting of the variable declarations to the top of the function has much less utility.
Some might argue that manually hoisting variables to the top of their scope makes things worse nowadays, if one accepts that const is strongly preferable to let (const variables cannot be reassigned; let variables can, making const variables easier for a programmer to internalize while reading code). For example, imagine having variables that depend on the value of other variables: refactoring the following
var startingNum, numMultipliedByTwo, plusOne;
startingNum = 2;
numMultipliedByTwo = startingNum * 2;
plusOne = numMultipliedByTwo + 1;
to ES6+, with manual hoisting, could only be done with let:
let startingNum, numMultipliedByTwo, plusOne;
startingNum = 2;
numMultipliedByTwo = startingNum * 2;
plusOne = numMultipliedByTwo + 1;
But since let doesn't have the same hoisting problems that var does, and since const is preferable to let, one may well conclude that this sort of style doesn't provide any benefit, and instead use:
const startingNum = 2;
const numMultipliedByTwo = startingNum * 2;
const plusOne = numMultipliedByTwo + 1;
constvariables cannot be declared without also assigning a value to them, so declaring variables all at once at the top before starting to assign to them and do things makes the use ofconstimpossible. (of course, one is free to not useconstat all, if one wishes, but that doesn't mean they have nothing to do with each other)