Arrow Function

- First question is : Can i use an anonymous function 

var names = ['Andrew','Julie','Jen'];

names.forEach(function (name) {
   console.log(name)
});

names.forEach((name) => {
    console.log(name)
});

names.forEach((name) => console.log(name));

var returnMe = (name) => name + '!';
console.log(returnMe('Andrew'));

--Anonymous function has a this binding, while arrow function takes their parents this binding 

Eg 1:

var person = {
    name: 'Andrew',
    greet: function () {
        names.forEach(function (name) {
            console.log(this.name + 'say hi to ' + name)
        })      
    }
};

person.greet();

Outcome: 

undefined say hi to Andrew
undefined say hi to Julie
undefined say hi to Jen

When we created the anonymous function, we have succesfully updated the this binding,
that means when we use the 'this' keyword, it does not refer to what we think it does  

Arrow function fixes this, as arrow function does not update the this keyword: 
The 'this' keyword still refers to the person object 
var person = {
    name: 'Andrew',
    greet: function () {
        names.forEach((name) => {
            console.log(this.name + ' say hi to ' + name)
        })      
    }
};

person.greet();

Outome:

Andrew say hi to Andrew
Andrew say hi to Julie
Andrew say hi to Jen

var addStatement = (a, b) => {
    return a + b;
};
console.log(addStatement(4,7));

var addExpression = (a,b) => a + b;
console.log(addExpression(4,7));

results matching ""

    No results matching ""