this in arrow functions code example

Example 1: 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)
    }
}

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: how to make javascript function consise

multiplyfunc = (a, b) => { return a * b; }

Example 5: javascript this inside arrow function

function A() {
  this.val = "Error";
  (function() {
    this.val = "Success";
  })();
}

function B() {
  this.val = "Error";
  (() => {
    this.val = "Success";
  })();
}

var a = new A();
var b = new B();
a.val // "Error"
b.val // "Success"

Example 6: arrow function

// Traditional Function
function (a){
  return a + 100;
}

// Arrow Function Break Down

// 1. Remove the word "function" and place arrow between the argument and opening body bracket
(a) => {
  return a + 100;
}

// 2. Remove the body brackets and word "return" -- the return is implied.
(a) => a + 100;

// 3. Remove the argument parentheses
a => a + 100;