What are the differences between the following function declaration formats? When is it more correct to use which?
From a beginner's perspective, and a high level (non-deep) point of view, they all three appear to work the same - hence it makes things feel confusing and demands the question.
1.
const counter1 = function(num) {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
2.
function counter2(num) {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
3.
const counter3 = (num) => {
var x = 0;
while (x < num) {
console.log(x);
x ++;
};
return 0;
};
All of them appear to behave the same.
There are more than a few differences between your three examples actually.
So, for one, you have to be careful using const for your function declarations.
Whereas the function will be hoisted and available for use (Edit: technically
let
andconst
are also hoisted, but they aren't initialized so you cannot access them before they are declared, more info here.Also note that
const
prohibits reassigning the variable, so you couldn't go sayconst counter1 = {}
later down the line, whereas you could feasibly do so with thefunction
example.As far as the difference between
function(num) {
versus(num) => {
, well in your example it makes no difference. But there are some differences... for exampleIf you're unfamiliar with the
arguments
object, you can find info here.