Skip to content

Instantly share code, notes, and snippets.

@HashirHussain
Created September 6, 2018 16:44
Show Gist options
  • Save HashirHussain/9ea71513ae6a9e937da9288cc938c0dd to your computer and use it in GitHub Desktop.
Save HashirHussain/9ea71513ae6a9e937da9288cc938c0dd to your computer and use it in GitHub Desktop.
Provide quick understanding of ES6 Arrow functions.
/*
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