Created
September 6, 2018 16:44
-
-
Save HashirHussain/9ea71513ae6a9e937da9288cc938c0dd to your computer and use it in GitHub Desktop.
Provide quick understanding of ES6 Arrow functions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Arrow functions are a shorthand for anonymous functions in JavaScript. | |
Unlike function, arrows share the same lexical `this` as their surroundings bodies. | |
*/ | |
//Expression bodies | |
var result = items.map(v => v + 1); | |
var result = items.map((v, i) => v + i); | |
var result = items.map((v, i) => ({item: v, key: i})); | |
//Statement body | |
items.forEach(item => { | |
if(item % 2 === 0){ | |
result.push(item); | |
} | |
}); | |
//Lexical body | |
var student = { | |
name: 'Hashir', | |
subjects: [], | |
printSubjects() { | |
this.subjects.forEach(sub => { | |
console.log(`${this.name} knows ${sub}`); | |
}); | |
} | |
}; | |
student.subjects = ['Math', 'Science', 'English']; | |
console.log(student.printSubjects()); | |
/*print: | |
Hashir knows Math | |
Hashir knows Science | |
Hashir knows English | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment