javascript types of arrow functions code example

Example 1: 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 2: Arrow Functions

// The usual way of writing function
const magic = function() {
  return new Date();
};

// Arrow function syntax is used to rewrite the function
const magic = () => {
  return new Date();
};
//or
const magic = () => new Date();

Example 3: arrow func in javascript

const greet = (who) => {
  return `Hello, ${who}!`;
};

greet('Eric Cartman'); // => 'Hello, Eric Cartman!'

Example 4: javascript arrow function

let errow = () => {
  //the code you want to return;
};
Or
let errow = ('paramiter') => {
//the code you want to return
}

Example 5: arrow function javascript

const power = (base, exponent) => {
  let result = 1;
  for (let count = 0; count < exponent; count++) {
    result *= base;
  }
  return result;
};

//if the function got only one parameter

const square1 = (x) => { return x * x; };
const square2 = x => x * x;

// empty parameter

const horn = () => {
  console.log("Toot");
};