Fat Arrow Functions JavaScript Programming Tutorial
Welcome to the crash course on using the new Arrow functions in JavaScript, introduced in ECMAscript Edition 6 to provide a new approach to writing anonymous functions. Arrow functions have 2 major advantages over traditional anonymous functions. (a) They reduce the amount of code you need to write. (b) In object oriented programming, the "this" keyword always refers to the object no matter how many anonymous functions are nested in the class. We will demonstrate these concepts through code right now starting with the most basic.
They are Anonymous functions. Anonymous functions are functions that have no name like normal functions do. We see them used as parameters in methods that expect executable code as an argument. Anonymous functions are used in object oriented programming, or they are sometimes supplied as the value of a named variable.
We will compare traditional Anonymous function syntax with arrow function syntax side by side using several simple examples in order to demonstrate where, when and how to use arrow functions where you normally use anonymous functions.
Used as the value of a named variable
Traditional anonymous function that does not take in arguments.var x = function() { alert("executable code"); };
x();
Arrow function that does not take in arguments.
var x = () => { alert("executable code"); };
x();
Traditional anonymous function that takes in a single argument.
var x = function(a) { return a; };
alert( x(5) );
Arrow function that takes in a single argument.
var x = a => a;
alert( x(5) );
Traditional anonymous function that takes in multiple arguments.
var x = function(a,b,c) { return a + b + c; };
alert( x(2,5,1) );
Arrow function that takes in multiple arguments.
var x = (a,b,c) => a + b + c;
alert( x(2,5,1) );
Used in object oriented class programming
Anonymous arrow functions resolve the "this" issue when nesting anonymous functions in a class. "this" will always refer to the class object even if we use anonymous functions nested within the class.
Traditional anonymous function in a class.function Car(){
this.speed = 0;
var self = this;
setInterval( function(){
self.speed++;
document.getElementById("status").innerHTML = self.speed;
}, 300);
}
var car1 = new Car();
Arrow function in a class.
function Car(){
this.speed = 0;
setInterval( () => {
this.speed++;
document.getElementById("status").innerHTML = this.speed;
}, 300);
}
var car1 = new Car();