Traditional vs. arrow functions: when to use?

I’m currently working on the JavaScript Fundamentals code challenges (canIVote(), agreeOrDisagree(), lifePhase(), etc.), and I find myself unsure of whether the instructions in this module are lacking, or whether I’ve just missed something key and am clueless.

The code solutions in many of the challenges indicate that I’m supposed to be using arrow functions, and that seems to be treated as a given. And then suddenly in the howOld() challenge it switched back to traditional functions, and I’m not sure how I’m supposed to know which is called for when, or what best practices are there. It isn’t intuitive to me yet, and I don’t know if that’s down to inexperience or because there’s some hole in my knowledge, and I’m getting very frustrated.

Actually, the course as a whole has felt like it follows a similar format, with instructions being given step by step accompanied by a satisfactory amount of supporting context, except for every so often when suddenly it’s just like, “Okay, do the thing” in weirdly vague terms.

Any insight? Is this just a me problem?

Traditional function syntax should be used when you need to use the this property on functions or objects. They should also be used when you need hoisting (that’s where you can call a function earlier in the code before it has been officially declared). Finally, traditional syntax is often used for Immediately Invoked Function Expressions (IIFEs) - I won’t go into detail as the uses for IIFEs are few and far between these days, but feel free to give it a Google.

Arrow functions are most often used for simple functions that make use of the implicit return syntax.

However, outside of these niche uses, you may freely use whatever you feel more comfortable with. But do keep in mind the use of this when dealing with an existing codebase, as arrow functions do not play well with this.

While arrow functions are compact and great for short, simple functions, traditional functions are more versatile and suitable for defining methods and constructors. When using ‘this’ binding, traditional functions should be used. In contemporary JavaScript, arrow functions should be used for small, anonymous functions. In your code, make a decision based on context and purpose.