3 ms·
Can someone explain this interesting snippet? const h1 = () => makeElement(`h1`);
by tomcam 10y ago
Can someone explain this interesting snippet?
const h1 = () => makeElement(`h1`);
- k__ 10y agobefore you have to write makeElement(`h1`) everywhere after this declaration you can write h1() instead just a shortcut function
- tomcam 10y agoSorry, it was the syntax up to the makeElement(`h1`); that I didn't understand: const h1 = () => Is this new syntax declaring a function named h1 that returns a function or what? I don't understand what the empty pair of parentheses means.
- k__ 10y agoYes, this is a shortcut for: const h1 = function() { return makeElement('h1'); } Arrow functions without arguments need empty paranthesis. They also have an implicit return if you don't use {}
- teniutza 10y agoYes, it's ES6/ES2015. It's a lambda function ("fat arrow notation"). In the parentheses you would specify the arguments. An empty pair of parentheses means that the function does not expect any parameters.
- tomcam 10y agoOK, thanks. So it is the parameter list, not the return value
- pluma 10y agoTo add to the other explanations: it's also important to point out that arrow functions are slightly different from regular functions in that they don't redefine `arguments` and `this` so these keywords behave like any other variable would in a closure. So it's not just a syntactic shorthand but there's also a semantic difference.
- mattnewton 10y agoThis is declaring a constant and assigning a function that takes no arguments to that constant.
- teniutza 10y agoIt Uses "fat arrow" functions (lambdas) to define function. It is "equivalent" (there are several differences here, like "const" and the context of the function) to: var h1 = function() { return makeElement(`h1`); } Edited to reflect the valid point brought up in the comments
- tomcam 10y agoAh, thanks a ton. Everything I looked up was too general to help!
- closetnerd 10y agoTechinically you're missing a return.
- drdaeman 10y agoNot really an equivalent, because "this" would be different - unlike with function(){}, there is no automatic this-context binding with arrows, so just switching to a fancier syntax in existing code may break things. Also, no "arguments" (there are ...rest parameters that allow for variadic functions).
- divbit 10y ago> no automatic this-context binding with arrows, I thought the arrows were now binding to surrounding context? (e.g. https://babeljs.io/blog/2015/06/07/react-on-es6-plus https://babeljs.io/blog/2015/06/07/react-on-es6-plus)
- nicoburns 10y agoIt is equivalent in this case though, as the function body doesn't use any of those features...