arrow function js code example

Example 1: arrow function javascript

// Normal Function in JavaScript
function Welcome(){
  console.log("Normal function");
}

// Arrow Function
const Welcome = () => {
  console.log("Normal function");
}

Example 2: arrow function rec

(param1, param2,, paramN) => { statements } 
(param1, param2,, paramN) => expression
// equivalent to: => { return expression; }

// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements }
singleParam => { statements }

// The parameter list for a function with no parameters should be written with a pair of parentheses.
() => { statements }

Example 3: javascript arrow function

// Non Arrow (standard way)
let add = function(x,y) {
  return x + y;
}
console.log(add(10,20)); // 30

// Arrow style
let add = (x,y) => x + y;
console.log(add(10,20)); // 30;

// You can still encapsulate
let add = (x, y) => { return x + y; };

Example 4: js arrow function

// const add = function(x,y) {
//     return x + y;
// }

// const add = (x, y) => {
//     return x + y;
// }

const add = (a, b) => a + b;


const square = num => {
    return num * num;
}

// const rollDie = () => {
//     return Math.floor(Math.random() * 6) + 1
// }

const rollDie = () => (
    Math.floor(Math.random() * 6) + 1
)

Example 5: es6 arrow function

const multiplyES6 = (x, y) => x * y;

Example 6: js arrow function this

const person = {
    firstName: 'Viggo',
    lastName: 'Mortensen',
    fullName: function () {
        return `${this.firstName} ${this.lastName}`
    },
    shoutName: function () {
        setTimeout(() => {
            //keyword 'this' in arrow functions refers to the value of 'this' when the function is created
            console.log(this);
            console.log(this.fullName())
        }, 3000)
    }
}