Denis Jakus

making tech less cryptic

CTO x Unique People

Denis Jakus

making tech less cryptic

CTO x Unique People

CTO Note

Arrow Functions1 min read

16 September 2017 Javascript
Arrow Functions1 min read

What is arrow function?

In short, it’s a shorthand for writing function in which “this” input returns “this” output. Additional to already stated, we can leave return keyword but only in certain cases.
Benefits of using arrow functions is definetly shorter syntax ie.
If we have no input we write syntax like this:

[syntax_prettify]var calculate = () => 2+5; // logs "7"[/syntax_prettify]

If we have one argument, we can leave parentheses i.e.:

[syntax_prettify linenums="linenums"]var calculate = count => count * 2;
console.log(calculate(2)) // logs "4"[/syntax_prettify]

If we have multiple arguments we use parentheses:

[syntax_prettify linenums="linenums"]var calculate = (val1, val2) => val1 * val2;
console.log(calculate(2,4)) // logs "8"[/syntax_prettify]

If we dont have a single expression we can specify a block and in that case we need to use return keyword.

[syntax_prettify linenums="linenums"]var calcualte = (val1, val2) => { 
var result = (val1 / 100) + (val2 * 10);
return result;
}[/syntax_prettify]

SUMMARY:

  • Real purpose of arrow functions is to handle this keyword (sets the context to the code we are running and not context of a function)
  • When using arrow functions we are not able to use bind/call/apply to change this context
  • it is not possible to set arrow (=>) in a new line! Everything must be written in single line
Taggs:
Related Posts
Learn how to use async inside useEffect hook

Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like Did you stumble upon a…

Javascript Splice VS Javascript Slice

Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like Little chit-chat Hi! Let me…

Write a comment