this keyword in arrow function 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 function in javascript

//function old way
function PrintName(name){
  console.log("my name is ", name) ;
}
// Arrow function es6
const PrintName =  (name) => {
  return console.log("my name is " , name) ;
}

Example 3: 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 4: arrow function javascript

/* Answer to: "arrow function javascript" */

// Single-line:
let testingFunc(string) => string == "Test" ? "Success!" : "Failure!";
console.log(testingFunc("test")); // "Failure!"

// Multi-line:
let arrowFunc(string) => {
  if (string = "test") {
    return "Success!";
  }
    return "Failure!";
  }
};
console.log(testingFunc("Test")); // "Success!"

/*
  Arrow functions in JavaScript are like regular functions except they look
  look nicer (imo) and there's single-line version of it which implicitly
  returns.
  
  Here's a guide showing the differences between the two:
  https://medium.com/better-programming/difference-between-regular-functions-and-arrow-functions-f65639aba256
  > The link will also be in the source below.
*/

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

Arrow Function is another way to write a function.
"classic method":
function x ()
{
	console.log("X")
}
"arrow method":
var x= ()=>
{
	console.log("X")
}
if we need to add paramiter is pritty simple:
var x = (PARAMS) =>
{
	console.log(PARAMS)
}
Have a nice day