Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 8, 2020 06:54 pm GMT

Arrow functions: a walkthrough and gotchas

In this blog post I show how to transform a traditional function into a so-called 'arrow function'. I start with functions with two arguments, then cover no arguments and finally, one argument.

Two arguments

  1. this is our function we want to transform:
    function sum(num1, num2){    return num1 + num2}
  2. now, arrow functions are anonymous so in order to preserve the name, we need a variable:
    const sum
  3. Now, put an = between the name and the arguments, and a => between the arguments and {}
    const sum = (num1, num2) => {  return num1 + num2}
  4. This already works! However, since the body of the function has only line, we can write it like this:
    const sum = (num1, num2) => { return num1 + num2 }
  5. And now, since this is only one line, we can simplify it:
    const sum = (num1, num2) => num1 + num2

    WHAT?! NOW RETURN?! Yes. You need a return statement as soon as there are {} in the picture and you need {} as soon as you have more than 1 line of function body

  6. No arguments

    If you have no arguments, here's how you can go about it:

    function helloWorld(){ console.log("Hi")}

    you can make it:

    const helloWorld = () => console.log("Hi") 

    or:

    const helloWorld = _ => console.log("Hi")  

    NOTE: the difference is that () says there might be some default argument and _ says there will for sure be no defaults but its a niche thing and no one uses it even in obscure dev

    One argument

    When it comes to just one argument:

    function myName(name){ console.log(`Hi, my name is ${name}`)}

    can be:

    const myName = name => console.log(`Hi, my name is ${name}`)

    since its just one argument, it doesnt need parenthesis

    Cover picture by Pexels


Original Link: https://dev.to/sylwiavargas/arrow-functions-a-walkthrough-and-gotchas-4p4p

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To