r/JavaScriptTips • u/[deleted] • May 09 '20
Why use => instead of function()
Hi, learning ES6 right now on freecodecamp and I am a bit confused. It provides this:
const myFunc = function() { const myVar = "value"; return myVar; }Stating it can be written as this instead:
const myFunc = () => "value";I understand that if its a one off function and only a return needs to be executed, then you can simplify it with the arrow function syntax. Does that mean this is a work around to const not letting its variable identifier to be changed, so an empty function is created so myFunc can take on that value?
1
u/LucVolders Jun 27 '20
More and more functions in Javascript are introduced with just one purpose: making your code more obscure. The reason for this is that a programmer surely does not want other pprogrammers to understand their code ;)
1
1
1
u/qwertymerty12345 Jul 16 '20
Arrow functions don't have their own this. The this value of the enclosing scope is used.
2
u/cyberjds Jun 06 '20
Call me a n00b, but I really don't get examples like op. Or maybe it's because I'm coming from procedural programming background, but what do they mean 'one off function'? Doesn't a function should be reusable? To my understanding, function is used to hide every little details and complexities so that it's easy to understand, and follow the main flow of the code.
Given above example, I can't help myself but ask, why don't I just do...
instead of declaring a function?
Give me an actual example that shows why arrow function expression is beneficial.
All I can smell is 'Functional', but I don't know what it is.