What are javascript arrow functions?



  • They are a shorter way of writing functions, this functionality was added ES6.

    šŸ”“ IMPORTANT Arrow functions notes.

    • Arrow way of defining function does not have their own this and hence not best suited to object definitions.
    • If the function is a single statement you can omit the return and curly brackets.
    • They much be defined before they can be used.

    Taking into account the notes above, with arrow function you can remove the keywords function, return and the curly brackets.

    The following shows a normal function and the arrow function equivalent.

    const x = function(a, b) { 
      return a + b 
    }
    console.log(x(5, 5))
    
    const y = (a, b) => (a + b)
    console.log(y(5, 5))
    

    You are also likely to see this syntax of a function. Which will also equivalent, but some developers remove the curly brackets and return because it's just a single statement.

    const z = (a, b) => { return (a + b) }
    console.log(y(5, 5))
    


© Lightnetics 2024