JavaScript Functions: Arrow vs Regular

🏹 𝐓𝐡𝐞 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐅𝐚𝐜𝐞-𝐎𝐟𝐟: 𝐀𝐫𝐫𝐨𝐰 vs. 𝐑𝐞𝐠𝐮𝐥𝐚𝐫 If the this keyword feels like a riddle wrapped in a mystery, you aren’t alone! It’s one of the most confusing parts of JavaScript, but the secret lies in how you define your functions. Here is the breakdown of the two heavyweights and exactly when to use them: 1. 𝐑𝐞𝐠𝐮𝐥𝐚𝐫 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 (𝐓𝐡𝐞 𝐃𝐲𝐧𝐚𝐦𝐢𝐜 𝐃𝐮𝐨) 🔄 𝐒𝐲𝐧𝐭𝐚𝐱: function doSomething() { ... } 𝐓𝐡𝐞 '𝐭𝐡𝐢𝐬' 𝐁𝐞𝐡𝐚𝐯𝐢𝐨𝐫: It is dynamic. The value of this depends entirely on how the function is called (the caller). 𝐁𝐞𝐬𝐭 𝐅𝐨𝐫: Object methods or constructor functions where you need to access the object's own properties. 𝐓𝐡𝐞 𝐋𝐞𝐬𝐬𝐨𝐧: Use these when you want the function to have its own context. 2. 𝐀𝐫𝐫𝐨𝐰 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 (𝐓𝐡𝐞 𝐒𝐥𝐞𝐞𝐤 𝐒𝐡𝐚𝐫𝐩𝐬𝐡𝐨𝐨𝐭𝐞𝐫) 🎯 𝐒𝐲𝐧𝐭𝐚𝐱: const doSomething = () => { ... } 𝐓𝐡𝐞 '𝐭𝐡𝐢𝐬' 𝐁𝐞𝐡𝐚𝐯𝐢𝐨𝐫: It is lexical. They don’t have their own this. Instead, they "inherit" it from the surrounding code (the parent scope). 𝐁𝐞𝐬𝐭 𝐅𝐨𝐫: Callbacks (like .map() or .filter()), closures, and preserving context inside setTimeout. 𝐓𝐡𝐞 𝐋𝐞𝐬𝐬𝐨𝐧: Use these to keep your code concise and to avoid the "that = this" or .bind(this) hacks of the past. 🚩 𝐖𝐡𝐞𝐧 𝐍𝐎𝐓 𝐭𝐨 𝐮𝐬𝐞 𝐀𝐫𝐫𝐨𝐰 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬: Methods in Objects: If you use an arrow function as an object method, this will point to the global window/undefined instead of the object itself! Event Listeners: If you need this to represent the element that was clicked, stick to a regular function. 𝐓𝐡𝐞 𝐆𝐨𝐥𝐝𝐞𝐧 𝐑𝐮𝐥𝐞: Use Arrow Functions by default for their clean syntax and predictable context in callbacks. Switch to Regular Functions only when you specifically need a dynamic this (like in methods or constructors). Are you still using .bind(this) in 2026, or have you fully embraced the arrow? Let’s settle the debate below! 👇 #JavaScript #CodingTips #WebDev #SoftwareEngineering #ArrowFunctions #ProgrammingLogic #CleanCode

To view or add a comment, sign in

Explore content categories